I'am trying to match the following regex:
I have a String: F-F-W-F
i need to write a regex, that checks if the first char is a W or F followed by an - . To check the String F-F-W-F.
This is what i came up with:
if(SBAKTIV.matches("[WF]{1}-[WF]{1}-[WF]{1}-[WF]{1}")) {
SBAKTIVMessageForLog = "SBAKTIV: Okay";
return true;
As mentioned in the comments, your regex is good to go. Or perhaps can be shortened to ([WF]-)*[WF] or ([WF]-){3}[WF].
I'm only posting an answer to provide a non-regex based solution*, in case you end up wanting/needing one of those too:
for (int i = 0; i < word.length(); i++) {
if (i % 2 == 0) {
if (word.charAt(i) != 'F' && word.charAt(i) != 'W') {
return false;
}
} else if (word.charAt(i) != '-') {
return false;
}
}
return true;
Demo
*This is based obviously on the length being ok, not null and so on
Related
I have recursive string that goes like this,
var1=[[1,2,3], [1,2,3]], var2=true, var3="hello", var4=(var1=[[1,2,3], [1,2,3]], var2=true, var3="hello")
I want to separate the string by commas and desired result is this,
var1=[[1,2,3], [1,2,3]]
var2=true
var3="hello"
var4=(var1=[[1,2,3], [1,2,3]], var2=true, var3="hello")
I have tried this regex, (([a-zA-Z0-9]*)=(.*),?\s?)*, to match the something like this, varx=(), but the complete string was matched.
I also tried to do this by traversing the string but was not able to separate strings like varx="...." because the quotes can contain anythings so there was no way to do this.
public static int fun2(int start_index, String str, int end_index) {
Stack<Character> charStack = new Stack<>();
charStack.add(str.charAt(start_index));
char opp = ' ';
if (str.charAt(start_index) == '(') {
opp = ')';
} else if (str.charAt(start_index) == '[') {
opp = ']';
} else if (str.charAt(start_index) == '[')
while (end_index < str.length() && !charStack.isEmpty()) {
if (str.charAt(end_index) == str.charAt(start_index)) {
charStack.add(str.charAt(start_index));
} else if (str.charAt(end_index) == opp) {
charStack.pop();
}
end_index++;
}
if (charStack.isEmpty()) {
System.out.println("correct");
System.out.println(str.substring(start_index, end_index));
}
return end_index;
// throw error
}
public static void fun(String str) {
int start = 0;
int end = -1;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '=') {
System.out.println("key = " + str.substring(start, end + 1));
start = i + 1;
end = start + 1;
if (str.charAt(start) == '[' || str.charAt(start) == '(' || str.charAt(i) == '"') {
System.out.println("value = ");
end = fun2(start, str, end);
start = end;
i = start;
}
} else if (str.charAt(i) == ',' || str.charAt(i) == ' ') {
start++;
end++;
} else {
end++;
}
}
}
Can anyone suggest any regex or piece of code that will do this for me. Thanks in advance.
To get the matches in the example data, you could match the key part without matching an equals sign.
For the value you can either match from an opening till closing parenthesis, or match until the next key part or end of string.
Note that this pattern does not takes any recursion from the parenthesis or square brackets into account. It depends on matching the parenthesis or using the comma as a separator.
[^\s=,]+=(?:\([^()]*\)|.+?)(?=,\s*[^\s=,]+=|$)
Regex demo
In Java with the doubled backslashes
String regex = "[^\\s=,]+=(?:\\([^()]*\\)|.+?)(?=,\\s*[^\\s=,]+=|$)";
I am trying a program that translates your sentence into pig latin. Here's the code I have so far:
public class PigLatin {
public static void main(String[] args) {
//Enter text in the quotes of System.ot.println(covertToLatin(" "));
System.out.println(covertToLatin("Type your sentence here."));
}
private static String covertToLatin(String string) {
String end = "";
String delims = "\\s+";
String[] words = string.split(delims);
for (int i = 0; i < words.length; i++) {
if(isVowel(words[i].toLowerCase().charAt(0))) {
end += words[i] + "ay";
} else {
end += words[i].substring(1) + words[i].substring(0, 1) + "ay";
}
}
return end;
}
private static boolean isVowel(char c) {
if (c == 'a')
return true;
if (c == 'e')
return true;
if (c == 'i')
return true;
if (c == 'o')
return true;
if (c == 'u')
return true;
return false;
}
}
It translates "Type your sentence here." to "ypeTayouryayentencesayere.hay" I am stumped as to finding a way to translate my whole sentence. can you please help me translate a whole sentence into pig latin? Also, it would help if you could find a way to make the sentence convert in all caps too.
for upper case, use String.toUpperCase() function
Start by translating one word first and then a complete sentence. For example STACK should print out ACKSTAY. Your program prints out TACKSAY.
Why is this? Let's look at your logic:
for (int i = 0; i < words.length; i++) {
if(isVowel(words[i].toLowerCase().charAt(0))) {
end += words[i] + "ay";
} else {
/*substring(1) is always 1 &&
you add substring(0,1) which is always the interval (0,1) they never change*/
end += words[i].substring(1) + words[i].substring(0, 1) +ay";
}
}
return end.toUpperCase();
}
private static boolean isVowel(char c) {
if ((c == 'a') | (c == 'e') | (c == 'i') | (c == 'o') | (c == 'u'))
return true;
return false;
}
Try writing your algorithm on paper first. For example always using the word stack.
First letter is an s (not a vowel) let's save it in a temp string.
second letter is t ( not a vowel) let's save it in a temp string.
a is a vowel! we print from a onwards + letters in temp + ay
end result = "ack" + "st" + "ay"
abstracting --> substring(i, endOfString) + substring(k,i) + "AY
so you actually need two counters! i,k used to print substring(i,EndOfString) and substring(i,k) which represents the temp array
I have a string of characters with As and Bs that I need to analyze for a Language A^nB^n. I can use the following code to work most of the time but when there is a letter that is not an "A" or "B" it may still return true, for example: AABACABAA should not be true, but it says it is. AABB is true; AABBAABB is not true. I have to use stacks and am not allowed to use counting.
public static boolean isL2(String line){
// set up empty stacks
Stack L2Stack = new Stack();
// initialize loop counter
int i = 0;
int n = line.length();
/* Push all 'A's to a_stack */
while ((i < line.length()) && (line.charAt(i) == 'A')) {
char ch = line.charAt(i);
L2Stack.push(ch);
i++;
}
/* Pop an 'A' for each consecutive 'B' */
while ((i < line.length()) && (line.charAt(i) == 'B')) {
if (!L2Stack.empty()){
L2Stack.pop();
i++;
}
else
return false;
}
if (i == n && !L2Stack.empty()){
return false; // more As than Bs
}
if (i != n && L2Stack.empty()){
return false; //more Bs than As
}else
return true;
}
if (i != n && L2Stack.empty()) {
return false; //more Bs than As
}
Should be
if (i != n) {
return false;
}
Since if you haven't finished reading all the characters, you can't return true, regardless of whether or not the stack is empty.
I'm assuming that AAABBBA should return false.
That change would also handle illegal characters.
I'm just learning java, and I have an assignment where I have to write a program that checks the validity of expressions about sets. Valid expressions are capital letters, an expression with a tilde in front, and can be combined using + and x as well as with parentheses. I've written a program that almost works, but I can't figure out how to get the binary operators to work with the parentheses.
It may also be that I have approached the problem in the wrong way (trying to validate from left to right, ignoring everything to the left once it's been validated). I can use any help I can get about writing recursive programs for this sort of problem; that is, if you have any pointers for a better way of approaching the problem, that would be incredibly helpful.
For reference, here is the code that I have:
public static boolean check(String expr) {
char spot;
int close=0;
expr = expr.trim();
//base case
if (expr.length() == 1 && expr.charAt(0)>= 'A' && expr.charAt(0) <= 'Z')
return true;
if (expr.charAt(0) == '~') {
if (expr.charAt(1) == 'x' || expr.charAt(1) == '+' || expr.charAt(1) == ')')
return false;
return check(expr.substring(1));
}
if (expr.indexOf('x') > 0 && expr.indexOf('x') > expr.indexOf(')')) {
int x = expr.indexOf('x');
if (check(expr.substring(0, x)) && check(expr.substring(x)))
return true;
}
if (expr.indexOf('+') > 0 && expr.indexOf('+') > expr.indexOf(')')) {
int plus = expr.indexOf('+');
if (check(expr.substring(0, plus)) && check(expr.substring(plus+1)))
return true;
}
if (expr.charAt(0) == '(') {
close = findEnd(expr.substring(1));
if (close < 0)
return false;
if (check(expr.substring(1,close)) && check(expr.substring(close+1)))
return true;
}
return false;
}
I'm not sure why your code is that complex. Recursion for this is pretty simple overall; here's what I'd do:
public static boolean check(String str) {
if(str.equals("")) return true;
if(str.charAt(0).isAlphaNumeric() || str.charAt(0) == '(' || str.charAt(0) == ')') return check(str.substring(1));
return false;
}
Your edge cases are if the string is empty; if this is the case, then the string is valid. If the character doesn't match what you're looking for, return false. Otherwise, check the next character.
I'm doing an online CPS course and a question requires me to write a code that counts the vowels(upper and lowercase) in a string. Here is my code:
public static int countVowels( String s )
{
{
if ( s.length() == 0 )
return 0 + countVowels(s);
else if ( (s.substring(0, 1) == "a" ) || (s.substring(0, 1) == "A") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "e" ) || (s.substring(0, 1) == "E") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "i" ) || (s.substring(0, 1) == "I") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "o" ) || (s.substring(0, 1) == "O") )
return 1 + countVowels(s.substring(1));
else if ( (s.substring(0, 1) == "u" ) || (s.substring(0, 1) == "U") )
return 1 + countVowels(s.substring(1));
}
return countVowels(s.substring(1));
}
but I'm getting a "StackOverFlow" error and I'm not sure what to do. I know that the error means that the terminating condition isn't being reached. I'm not allowed to use anything that I haven't learned yet and I'm also not allowed to use for or while statements because this is a recursion problem.
Could I please get some help?
In the case when s.length() == 0 you are causing an infinite recursion. An empty string has 0 vowels, so you should edit 5th line to return 0; Another thing to watch out for: you're comparing strings with ==. This operator is intended for something else. Use equals instead. Take a look at this, for example: String comparison. That is s.substring(0, 1) == "a" should become s.substring(0, 1).equals("a")
As a matter of fact, there are some other pieces of advice I'd give you, like just storing the first letter in the string, instead of calculating it in every case (twice at that). Also, you can get the lower case character for the first character, so that you can reduce the cases you compare to twice. Also, add vowels to an array, this code is not DRY.
This is a possible solution in javascript. You can test it by creating a file 'something.html' and opening it in your browser.
<html>
<head></head>
<body>
<div id="input">
</div>
<div id='answer'>
</div>
<script>
var vowels = ['a','e','i','o','u'];
var testInput = 'Hello this is just a test. Out with it.';
function Contains(value, inArray) {
var found = false;
for(var j=0, size = inArray.length; j < size; j++) {
if(value.toLowerCase() === inArray[j]) {
found = true;
}
}
return found;
}
var vowelCounter = 0;
for(var i=0, j = testInput.length; i < j; i++) {
if(Contains(testInput[i], vowels)) {
vowelCounter +=1;
}
}
var inp = document.getElementById("input");
inp.innerHTML = 'Question <br/>' + testInput;
document.getElementById('answer').innerHTML = 'Number of Vowels: ' + vowelCounter;
</script>
</body>
</html>
I hope by now you would have completed your homework. I have solved the same problem in a shorter way:
public class CountVowels {
private static String vowels = "aeiou";
public static void main(String[] args){
String s = "RohanAskedAQuestion";
System.out.println(recursivelyCountVowels(s));
}
private static int recursivelyCountVowels(String s) {
if(s==null||s.length()==0)
{
return 0;
}
if(vowels.contains((CharSequence) s.substring(0, 1).toLowerCase())){
return 1+recursivelyCountVowels(s.substring(1));
}
return 0+recursivelyCountVowels(s.substring(1));
}
}
I hope it helps :) , I am also learning java so if anybody has any suggestion please do tell.
Thanks.
Maybe its a little late but still :)
public int recursiveCountVowels(String str,int count,int currentPosition)
{
str = str.toLowerCase();
if(str.trim().length() == 0)
return count;
if(currentPosition == str.length())
return count;
for(int i = currentPosition ; i < str.length();i++)
{
if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;
currentPosition++;
}
return recursiveCountVowels(str, count, currentPosition);
}
vowel count (vc) - Return the number of vowels in an input string.
public static int vc(String s)
{
if(s.length() - 1 < 0) return 0;
return((("aeiou".indexOf((s.charAt(s.length()-1)+"").toLowerCase()) >= 0 ? 1 : 0))
+ vc((s = s.substring(0,s.length()-1))));
}