I would like to find out if my string has = & & sequence in it. If yes then I would like to encode second &. How using java regex can I find it?
My string is something like this:
a=cat&b=dog&cat&c=monkey
Thanks Chaitanya
Like Mosty and Ted suggested, perhaps the best way to go at this is by detecting and escaping the '&'.
However, if you want a single regex to do the work for you, here it is:
String s = "a=cat&b=dog&cat&c=monkey";
s = s.replaceAll("&(?=[^=]*&)", "&");
System.out.println(s);
& (?=[^=]*&) The first section detects an '&', which is the character you want to replace. The second part is trickier. You need to make sure that after the '&' that you have just detected, the next sequence of characters contains another '&' and no '=' until that next '&'.(?=X) Where X is the condition that you want to test. In this case, X is: [^=]*& Or in other words: " any character that is no '=', zero or more times, followed by an '&' ". So in the end you get &(?=[^=]*&), which means: " an '&' for which the following sequence of characters has no '=' up until the next '&' ".You can use this format:
if (string.contains("=&&"))
{
// do something
}
else
{
// do something else
}
I don't know what you mean by "encode the &" though. Could you clarify?
It would be easier to escape the & in the values before forming the concatenated name-value pair string. But given an already-encoded string, I think a variant of Mosty's suggestion might work best:
String escapeAmpersands(String nvp) {
StringBuilder sb = new StringBuilder();
String[] pairs = nvp.split("&");
if (pairs[0].indexOf('=') < 0) {
// Maybe do something smarter with "a&b=cat&c=dog"?
throw new Exception("Can't handle names with '&'");
}
sb.append(pairs[0]);
for (int i = 1; i < pairs.length; ++i) {
String pair = pairs[i];
sb.append(pair.indexOf('=') < 0 ? "&" : "&");
sb.append(pair);
}
return sb.toString();
}
This is likely to be faster than regular trying to do this with regular expressions.
=&&in the string, or can there be other characters between the=,&, and the second&?