I have a list of strings that in a pattern like this:
128 and 228 and alpha > 200 and bravo < 400 or charlie = 400
Now I want to replace all occurrences of \\d+
, except when it is preceded by a relational operator (<|>|=)
. Otherwise the call to replaceAll
method on the string should replace all occurrences of \\d+
with s.$1
. So the above string would be transformed to something like:
s.128 and s.228 and alpha > 200 and bravo < 400 or charlie = 400
I have tried to achieve this with the following: (^\\d+|(?<!>|<|=)\\s+\\d+)
with no luck.
You can use negative-lookbehind mechanism.
We want to find and replace digits which don't have
>
OR <
OR =
with space before 200
00
part also doesn't have <
>
=
before we must add condition that we also don't want replace digits which have digits before them So your code can look like
replaceAll("(?<![>=<]\\s|\\d)\\d+", "s.$0")
BTW: You don't need to surround your regex to create separate group so you could use it via $1
since group 0
always contains entire match. Also look-around mechanisms are zero-length which means that they are not included in match.
Demo:
String text = "128 and 228 and alpha > 200 and bravo < 400 or charlie = 400";
text = text.replaceAll("(?<![>=<]\\s|\\d)\\d+", "s.$0");
System.out.println(text);
Output:
s.128 and s.228 and alpha > 200 and bravo < 400 or charlie = 400
I tried it out, worked fine for me:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.