For a given string
String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
How can we check if welcomeMessage contains "Welcome, you have notification" substring by escaping name variable as name variable keeps on changing?
I want to achieve
welcomeMessage.contains("Welcome, You have notification!"); //to return true
What would be the best way to skip name variable?
String#startsWith & endsWith
The String class provides specific methods:
startsWith
endsWith
Example:
boolean containsPhrases =
message.startsWith( "Welcome" )
&&
message.endsWith( ", You have notification!" )
;
very simple
String name = "Test";
String welcomeMessage = "Welcome" + name + ", You have notification!";
System.out.println(welcomeMessage + " matches " + welcomeMessage.matches("Welcome.+You have notification!"));
With matches on a regular expression. There are some special regex characters that need to be escaped with a backslash, twice \\ in a regex.
welcomeMessage.matches("Welcome .*, you have notification\\!");
.* stands for . = any character without line breaks, and * = repeat the previous 0 or more times. So any string.
Related
I have a string where it contains different combinations of the slashes
{"result":"{\"cov_details\":[{\"issue_date\":\"UNIT
OFFICE,NEYVELI\",\"cov\":\"MCWG\"}],\"dl_number\":\"TN31Y200000784\",\"address\":\"PERIYA COLONY KO
PAVAZHANGUDI VIRUDHACHALAM TK\",\"issue_date\":\"24-03-2010\",\"dob\":\"21-03-
1981\",\"name\":\"VICNESWARAN S\",\"blood_group\":\"\",\"validity\":{\"transport\":\"\",\"non-
transport\":\"4-01-2010 to 23-03-2040\"},\"father\\\/husband\":\"SELVAM\"}","status-
code":"101","request_id":"a2642ae9-2f10-4e9a-9f7e-c3ee1a9a2dbe"}
I want to replace all occurances of a single "" alone but ignore when "" is followed by "/" ( check out the father\\\/husband\ parameter. It should read father\/husband. How can I achieve this in Java?
Just hide "\/" by replacing it with another character sequence like "~~~", then restore it after:
String string = "father\\\\\\/husband\\";
System.out.println("Before\t:\t" + string);
System.out.println
(
"After\t:\t" + string
.replaceAll("\\\\/", "~~~")
.replaceAll("\\\\", "")
.replaceAll("~~~", "\\\\/")
);
Output:
Before : father\\\/husband\
After : father\/husband
public String replaceAll​(String regex, String replacement) accepts regex as the first parameter:
https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/String.html#replaceAll(java.lang.String,java.lang.String)
Fill free to specify any pattern you need:
https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/regex/Pattern.html#sum
I'm trying to split my string using regex. It should include even zero-length matches before and after every delimiter. For example, if delimiter is ^ and my string is ^^^ I expect to get to get 4 zero-length groups.
I can not use just regex = "([^\\^]*)" because it will include extra zero-length matches after every true match between delimiters.
So I have decided to use not-delimiter symbols following after beginning of line or after delimiter. It works perfect on https://regex101.com/ (I'm sorry, i couldn't find a share option on this web-site to share my example) but in Intellij IDEa it skips one match.
So, now my code is:
final String regex = "(^|\\^)([^\\^]*)";
final String string = "^^^^";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find())
System.out.println("[" + matcher.start(2) + "-" + matcher.end(2) + "]: \"" + matcher.group(2) + "\"");
and I expect 5 empty-string matches. But I have only 4:
[0-0]: ""
[2-2]: ""
[3-3]: ""
[4-4]: ""
The question is why does it skip [1-1] match and how can I fix it?
Your regex matches either the start of string or a ^ (capturing that into Group 1) and then any 0+ chars other than ^ into Group 2. When the first match is found (the start of the string), the first group keeps an empty string (as it is the start of string) and Group 2 also holds an empty string (as the first char is ^ and [^^]* can match an empty string before a non-matching char. The whole match is zero-length, and the regex engine moves the regex index to the next position. So, after the first match, the regex index is moved from the start of the string to the position after the first ^. Then, the second match is found, the second ^ and the empty string after it. Hence, the the first ^ is not matched, it is skipped.
The solution is a simple split one:
String[] result = string.split("\\^", -1);
The second argument makes the method output all empty matches at the end of the resulting array.
See a Java demo:
String str = "^^^^";
String[] result = str.split("\\^", -1);
System.out.println("Number of items: " + result.length);
for (String s: result) {
System.out.println("\"" + s+ "\"");
}
Output:
Number of items: 5
""
""
""
""
""
I want to match
String firstName = "CHRIS JAMES MR";
String prefix = "MR"; //mr Mr mR
firstName.matches("^(.*?)(?i)" + prefix + "$")
the current regex will return true even if it's
JOAmR
JOHN HOMR
wherein, it shouldn't.
So basically I'm trying to match
[anyNumberOfChar][anyNumberOfWhiteSpaces][anyCaseOf
"MR"]
I'm using java's String.matches
You could use a word boundary \b
^(.*?)(?i)\bMR$
firstName.matches("^(.*?)(?i)\\b" + prefix + "$");
Demo
I have a string
"#72c02c, #3498db, #e67e22, #9c8061, #4765a0, #79d5b3"
I want to convert it to the following:
"'#72c02c', '#3498db', '#e67e22', '#9c8061', '#4765a0', '#79d5b3'"
Is there any way to do so?
I don't know why everyone is using regex... this needs only a simple text replace:
str = "'" + str.replace(", ", "', '") + "'";
This just puts quotes before/after commas and puts a quote at each end, which is easy to understand.
String s = "#72c02c, #3498db, #e67e22, #e74c3c, #ecf0f1, #9b6bcc, #27d7e7, #9c8061, #4765a0, #79d5b3";
s = s.replaceAll("(#|,)","'$1");
if (s.charAt(s.length()-1) != ',')
s = s + "'";
Might not be the most elegant solution, but it handles the case of the final item in the string not ending with a ,. Will work if it does happen to end in a comma too.
If you are able to operate with it as with the simple String object instance, the you can do it with regex ([#\w]+) and String.replaceAll() method, like:
String testString = "#72c02c, #3498db, #e67e22, #e74c3c, #ecf0f1, #9b6bcc, #27d7e7, #9c8061, #4765a0, #79d5b3";
System.out.println(testString.replaceAll("([#\\w]+)","'$1'"));
Where with ([#\w]+), you just take every group of alpha-numeric characters or #
Then you just replace it with '$1', where $1 is the whole group, which was found.
I'm making a simple program that will deal with equations from a String input of the equation
When I run it, however, I get an exception because of trying to replace the " +" with a " +" so i can split the string at the spaces. How should I go about using
the string replaceAll method to replace these special characters? Below is my code
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
public static void parse(String x){
String z = "x^2+2=2x-1";
String[] lrside = z.split("=",4);
System.out.println("Left side: " + lrside[0] + " / Right Side: " + lrside[1]);
String rightside = lrside[0];
String leftside = lrside[1];
rightside.replaceAll("-", " -");
rightside.replaceAll("+", " +");
leftside.replaceAll("-", " -"); leftside.replaceAll("+", " +");
List<String> rightt = Arrays.asList(rightside.split(" "));
List<String> leftt = Arrays.asList(leftside.split(" "));
System.out.println(leftt);
System.out.println(rightt);
replaceAll accepts a regular expression as its first argument.
+ is a special character which denotes a quantifier meaning one or more occurrences. Therefore it should be escaped to specify the literal character +:
rightside = rightside.replaceAll("\\+", " +");
(Strings are immutable so it is necessary to assign the variable to the result of replaceAll);
An alternative to this is to use a character class which removes the metacharacter status:
rightside = rightside.replaceAll("[+]", " +");
The simplest solution though would be to use the replace method which uses non-regex String literals:
rightside = rightside.replace("+", " +");
I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.
rightside = rightside.replaceAll("\\+", " +");
String#replaceAll expects regex as input, and + is not proper pattern, \\+ would be pattern. rightside.replaceAll("\\+", " +");
The reason behind this is - There are reserved characters for regex. So when you split them using the java split() method, You will have to use them with escape.
FOr example you want to split by + or * or dot(.) then you will have to do it as split("\+") or split("\*") or split("\.") according to your need.
The reason behind my long explanation on regex is -
YOU MAY FACE IT in OTHER PLACES TOO.
For example the same issue will occur if you use replace or replaceAll methods of java Because they are also working based on regex.