Java regex to find a sequence of characters in a string
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?
开发者_StackOverflow社区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);
Why don't you just split it?
First split it by "&", then take the second element
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.
精彩评论