I have a base String "abc def", I am trying to replace my base string with "abc$ def$" using replaceFirst(), which is running into errors as $ is not escaped.
I tried doing it with Pattern and Matcher APIs, as given below,
newValue = "abc$ def$";
if(newValue.contains("$")){
Pattern specialCharacters = Pattern.compile("$");
Matcher newMatcherValue = specialCharacters.matcher(newValue) ;
newValue = newMatcherValue.replaceAll("\\\\$") ;
}
This runs into an error. Is there any elegant way of replacing my second string "abc$ def$" with "abc\\\\$ def\\\\$" so as to use the replacefirst() API successfully?
Look at Pattern.quote() to quote a regex and Matcher.quoteReplacement() to quote a replacement string.
That said, does this do what you want it to?
System.out.println("abc def".replaceAll("([\\w]+)\\b", "$1\\$"));
This prints out abc$ def$
You can use replaceAll just in one step:
String newValueScaped = newValue.replaceAll("\\$", "\\\\$")
$ has a special mining in regex, so you need to scape it. It's used to match the end of the data.
Related
I have this Java code
String cookies = TextUtils.join(";", LoginActivity.msCookieManager.getCookieStore().getCookies());
Log.d("TheCookies", cookies);
Pattern csrf_pattern = Pattern.compile("csrf_cookie=(.+)(?=;)");
Matcher csrf_matcher = csrf_pattern.matcher(cookies);
while (csrf_matcher.find()) {
json.put("csrf_key", csrf_matcher.group(1));
Log.d("CSRF KEY", csrf_matcher.group(1));
}
The String contains something like this:
SessionID=sessiontest;csrf_cookie=e18d027da2fb95e888ebede711f1bc39;ci_session=3f4675b5b56bfd0ba4dae46249de0df7994ee21e
Im trying to get the csrf_cookie data by using this Regular Expression:
csrf_cookie=(.+)(?=;)
I expect a result like this in the code:
csrf_matcher.group(1);
e18d027da2fb95e888ebede711f1bc39
instead I get a:
3492f8670f4b09a6b3c3cbdfcc59e512;ci_session=8d823b309a361587fac5d67ad4706359b40d7bd0
What is the possible work around for this problem?
Here is a one-liner using String#replaceAll:
String input = "SessionID=sessiontest;csrf_cookie=e18d027da2fb95e888ebede711f1bc39;ci_session=3f4675b5b56bfd0ba4dae46249de0df7994ee21e";
String cookie = input.replaceAll(".*csrf_cookie=([^;]*).*", "$1");
System.out.println(cookie);
e18d027da2fb95e888ebede711f1bc39
Demo
Note: We could have used a formal regex pattern matcher, and in face you may want to do this if you need to do this search/replacement often in your code.
You are getting more data than expected because you are using an greedy '+' (It will match as long as it can)
For example the pattern a+ could match on aaa the following: a, aa, and aaa. Where the later is 'preferred' if the pattern is greedy.
So you are matching
csrf_cookie=e18d027da2fb95e888ebede711f1bc39;ci_session=3f4675b5b56bfd0ba4dae46249de0df7994ee21e;
as long as it ends with a ';'. The first ';' is skipped with .+ and the last ';' is found with the possitive lookahead
To make a patter ungreedy/lazy use +? instead of + (so a+? would match a (three times) on aaa string)
So try with:
csrf_cookie=(.+?);
or just match anything that is not a ';'
csrf_cookie=([^;]*);
that way you don't need to make it lazy.
My regular expression is of format "Exit* Order*". When i use in java its not working as expected.
String pattern = "Exit* Order*";
String ipLine = "Exiting orders";
Match: NO
String pattern = "Exit Order";
String ipLine = "Exit order";
Match: Yes.
Java Code:
Pattern patrn = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
Matcher match = patrn.matcher(ipLine);
Can any one let me know what should be the pattern in such cases.
I believe you are looking for something like:
"Exit.* Order.*"
or maybe something instead of .*, e.g. \S*, \w*, [A-Za-z]*.
Your current regular expression is looking for zero or more t and r on the ends of the words, e.g. it would match
Exi Orde
Exit Orde
Exitt Orde
Exi Order
Exi Orderr
...
Exit\\w* Order\\w*
You should use this..* can match much more than intended.use i or ignorecase flag
It seems like you just want to match "Exit Order" case-insensitively:
Try this:
if (str.matches("(?i)exit order"))
Or to restrict the match to just your examples, where the "O" of "Order may be "o", use:
if (str.matches("Exit [Oo]rder"))
Java does not use Linux regexp expression:
http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
Use this:
String pattern = "Exit.* Order.*";
I have a string that looks like this:
String pathTokenString = "CMS/{brandPath}/Shows/{showPath}";
I want to remove the Shows part and everything that follows. I also want to replace "{brandPath}" with a token that I'm given.
This has been my approach. However, my string isn't getting updated at all:
//remove the '/Shows/{showPath}'
pathTokenString = pathTokenString.replace("/Shows$", "");
//replace passed in brandPath in the tokenString
String answer = pathTokenString.replace("{(.*?)}", brandPath);
Is there something wrong with my regular expressions?
You should use the replaceAll method instead of replace when you want to pass a regex string as the pattern to be replaced. Also your regex patterns should be updated:
pathTokenString = pathTokenString.replaceAll("/Shows.*$", "");
// The curly braces need to be escaped because they denote quantifiers
String answer = pathTokenString.replaceAll("\\{(.*?)\\}", brandPath);
I am not soo good in RegEx. Can somebody help me to to replace
<MessageParam name="0" desc="Source Queue" />
with
<MessageParam name="0" desc="Source Queue"></MessageParam>
using regular expression
Regex to match:
(<\s*MessageParam[^>]*)/\s*>
Replacement string:
$1></MessageParam>
You may need to escape the \ character (add an extra \ before it).
I assume > does not appear in the value for the attributes, and the XML is valid.
More generalized version:
Regex to match:
<\s*([^\s>]+)([^>]*)/\s*>
Replacement string:
<$1$2></$1>
For this one, I'm not sure of all the assumptions that I have made. But I still assume > does not appear in the value for the attributes, and the XML is valid.
Regex
<(\w+)(.+?)/>
replace with
<$1$2></$1>
public static void format(String xmlNode) {
Pattern patt = Pattern.compile("(<MessageParam[^>]*)(\\s*/>)");
Matcher mattcher = patt.matcher(xmlNode);
while (mattcher.find()){
String result = mattcher.replaceAll("$1></MessageParam>");
System.out.println(result);
}
}
This worked for me:
xmlString.replaceAll("<(\\w*:*\\w+)/>", "<$1></$1>");
I have a String say
String s = "|India| vs Aus";
In this case result should be only India.
Second case :
String s = "Aus vs |India|";
In this case result should be only India.
3rd case:
String s = "|India| vs |Aus|"
Result shouls contain only India, Aus. vs should not present in output.
And in these scenarios, there can be any other word in place of vs. e.g. String can be like this also |India| in |Aus|. and the String can be like this also |India| and |Sri Lanka| in |Aus|. I want those words that are present in between two pipes like India, Sri Lanka , Aus.
I want to do it in Java.
Any pointer will be helpful.
You would use a regex like...
\|[^|]+\|
...or...
\|.+?\|
You must escape the pipe because the pipe has special meaning in a regex as or.
You are looking at something similar to this:
String s = "|India| vs |Aus|";
Pattern p = Pattern.compile("\\|(.*?)\\|");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(m.group(1));
}
You need to use the group to get the contents inside the paranthesis in the regexp.