java regex to match variable - java

I have the name of a java variable in a string. I want to replace it with the letter x. How can I do this java, and make sure that other words in the string are not replaced ?
For example, say my variable is res, and my string is "res = res + pres + resd + _res. I want the string to become x = x + pres + resd + _res.

You can use a word boundary to only capture whole words:
String s = "res = res + pres + resd + _res";
String var = "res";
System.out.println(s.replaceAll("\\b" + var + "\\b", "x"));
outputs x = x + pres + resd + _res

You can use the \b metacharacter to match a word boundary. (Bear in mind you'll need to use doule backslashes to escape this in Java.)
So you can do something like the following:
final String searchVar = "res";
final String replacement = "x";
final String in = "res = res + pres + resd + _res";
final String result = in.replaceAll("\\b" + searchVar + "\\b", replacement);
System.out.println(result);
// prints "x = x + pres + resd + _res"

Related

very new to the programming and at the little exercise I cannot see where I am wrong

So maybe many of you knows the exercise we need to do about learning primitives, where we need to print h3110 w0r1d 2.0 true
so mine is this;
public class main {
public static void main(String[] args) {
// H3110 w0r1d 2.0 true
byte bir = 0;
short iki = 31;
int uc = 10;
long dort = 1;
float bes = 2.0f;
char yedi = 'H';
char sekiz = 'w';
char dokuz = 'd';
char ekstra = ' ';
char ramk = 'r';
boolean on = true;
String son = (yedi + iki + uc + ekstra + sekiz + bir + ramk + dort + dokuz + ekstra + bes + ekstra + on );
System.out.println(son);
}
}
and their solution is this;
public class Main {
public static void main(String[] args) {
byte zero = 0;
short a = 3;
int b = 1;
char d = ' ';
float e = 2.0f;
boolean f = true;
String output = "H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
System.out.println(output);
}
}
So mine is giving me boolean and float errors, but I cant see what is wrong with that primitives.
the error Im getting is this
Main.java:16: error: bad operand types for binary operator '+'
String son = (yedi + iki + uc + ekstra + sekiz + bir + ramk + dort + dokuz + ekstra + bes + ekstra + on );
^
first type: float
second type: boolean
1 error
The line:
String son = (yedi + iki + uc ...
assigns a concatenation of multiple parameters of different types, none of which is a string, into a string.
The "solution" is to start the assignment by concatenating a string to the other parameters:
String output = "H" + a + b + ...
^
which will cast the rest of them - to strings.
You can do the same with the first example by adding an empty string at the beginning:
String son = ("" + yedi + iki + uc ...
^
Side-Note: I totally agree with T.J. Crowder's comment above...
The example works because everything can be automatically converted to a String, and addition is left-associative.
The difference between a char and a String may not be obvious to you. 'C' is a char literal, while "C" is a String literal (which can contain multiple chars).
Let's go through a few steps of the string concatenation in the example, showing conceptually how the addition is performed:
"H" + a + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H3" + b + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H31" + b + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H311" + zero + d + "w" + zero + "r" + b + "d" + d + e + d + f;
"H3110" + d + "w" + zero + "r" + b + "d" + d + e + d + f;
...and so on. Every addition will always be a String + some other value, which is fine.
The addition in your code, on the other hand, tries to add incompatible types like int and boolean, which doesn't fly. Also, it tries to store the result in a String variable, which is not possible, because the result is not a String.

Break up the text on the page

I have a string
String str = "line1"+"\n" +
"line2"+"\n" +
"line3"+"\n" +
"line4"+"\n" +
"line5"+"\n" +
"line6"+"\n" +
"line7"+"\n" +
"line8"+"\n" +
"line9"+"\n" +
"line10"+"\n" +
"line11"+"\n" +
"line12"+"\n" +
"line13"+"\n" +
"line14"+"\n" +
"line15"+"\n" +
"line16"+"\n" +
"line17"+"\n";
I want to get out of it an array of strings
String str1 = "line1"+"\n" +
"line2"+"\n" +
"line3"+"\n" +
"line4"+"\n";
String str2 = "line5"+"\n" +
"line6"+"\n" +
"line7"+"\n" +
"line8"+"\n";
String str3 = "line9"+"\n" +
"line10"+"\n" +
"line11"+"\n" +
"line12"+"\n";
String str4 = "line13"+"\n" +
"line14"+"\n" +
"line15"+"\n" +
"line16"+"\n";
String str5 = "line17"+"\n";
if I do so
String[] str1 = str.split("\n");
I get an array of strings, in which only one line, and I need it for a few
instead of the string I will have the file from which I plan to read the text in a row
for splitting string with particular format you need to specify regular expression
so in your case regular expression will be ("\r\n")
Look Here

Regex for validating numbers with certain length and beginning

I would like to validate a value which should have numbers only and length should be 11 and should not start with 129.
Is this possible as I am not very efficient in regular expressions?
Use negative lookahead. The regex should be ^(?!129)\d{11}$ Turn that into a Java pattern; escape the backslash.
You can use
String num_regex = "^(?!129)\\b[0-9]{11}\\b";
String testString= "12345678910";
Boolean b = testString.matches(num_regex);
System.out.println("String: " + testString + " :Valid = " + b);
testString= "12945678910";
b = testString.matches(num_regex);
System.out.println("String: " + testString + " :Valid = " + b);
OUTPUT:
String: 12345678910 :Valid = true
String: 12945678910 :Valid = false

Split string on spaces and dash but not on the value of the string

I am setting a date_string like this:
gridcell.setTag(theday + "-" + themonth + "-" + theyear + "|" + hijri_day + "-" + hijri_month + " ("+ hijri_monthno +") " + hijri_year);
And I am splitting it like this:
String date_month_year = (String) view.getTag();
String[] dateAr = date_month_year.split("-|\\||\\(|\\)|\\s+");
This is also splitting the spaces and dash in the hijri month names i.e. Rabi al-Thani or Dhul Hijjah:
private String months[] = {"Muharram","Safar","Rabi al-Awwal","Rabi al-Thani","Jumada al-Awwal","Jumada al-Thani","Rajab","Sha\'ban","Ramadhan","Shawwal","Dhul Qa\'dah","Dhul Hijjah"};
How do I split on the date_string only and not the value of the strings in the date_string?
best way is changing the date separator - to / (slash) or .(dot) If you really wanna keep like this, than after split you can check last character on string array if it is a letter join that two string into one back..
gridcell.setTag(theday + "." + themonth + "." + theyear + "|" + hijri_day + " " + hijri_month + " ("+ hijri_monthno +") " + hijri_year);
make it like this easiest way..
I tried to split your date step by step so check if this works for you
List<String> tokens=new ArrayList<String>();
String data="theday-themonth-theyear|hijri_day-Dhul Qa\'dah (hijri_monthno) hijri_year";
String[] tmp = data.split("\\|");
//System.out.println(Arrays.toString(tmp));
for (String s:tmp[0].split("-"))
tokens.add(s);
System.out.println(tokens);// -> [theday, themonth, theyear]
String[] tmp2=tmp[1].split("\\s*\\(|\\)\\s*");
//System.out.println(Arrays.toString(tmp2));
for (String s:tmp2[0].split("-",2))
tokens.add(s);
System.out.println(tokens);// -> [theday, themonth, theyear, hijri_day, Dhul Qa'dah]
tokens.add(tmp2[1]);
tokens.add(tmp2[2]);
System.out.println(tokens);// -> [theday, themonth, theyear, hijri_day, Dhul Qa'dah, hijri_monthno, hijri_year]

Java: Why is my obscenity filter replacing all last words that end in 'a' in my chat sessions?

I am using Java and I created obscenity filter that works well except if we have a letter that ends in a it will be replaced.
eg. "I want a banana" --> "I want a bananbleep"
HOWEVER...
If you add punctuation after the 'a' it will show up correctly.
eg. "Would you like a banana?" --> "Would you like a banana?"
Here is what I did:
public String rInString(String theDisplay) {
String a = theDisplay;
String b = word;
String c = Matcher.quoteReplacement(replacement);
if(matchWholeWord != null && matchWholeWord){
b = "([^\\p{Alpha}\\p{Lower}\\p{Space}])" + b +
"([^\\p{Alpha}\\p{Lower}\\p{Space}])";
a = " " + a + " ";
c = "$1" + c + "$2";
}
return message.replaceAll("(?i:" + b + " )", c).trim();
}
public String rInString(String theDisplay, String theB, String replace) {
String c = Matcher.quoteReplacement(replace);
String a = theDisplay;
String b = theB;
if (matchWholeWord != null && matchWholeWord) {
b = "([^\\p{Alpha}\\p{Space}])" + b + "([^\\p{Alpha}\\p{Space}])";
a = " " + a + " ";
c = "$1" + c + "$2";
}
return message.replaceAll("(?i:" + b + ")", c).trim();
}
The issue was that one letter (a) was being blocked because $$ are the terminus in the RegEx statement. This meant that the a was being counted as a bad element. Each $ needed to be escaped in the SQL statement.

Categories

Resources