开发者

java regex how to match some string that is not some substring

开发者 https://www.devze.com 2023-04-11 08:39 出处:网络
For example, my org string is: CCC=123 CCC=DDDDD CCC=EE CCC=123 CCC=FFFF I want everything that does not equal to \"CCC=123\" to be changed to \"CCC=AAA\"

For example, my org string is:

CCC=123
CCC=DDDDD
CCC=EE
CCC=123
CCC=FFFF

I want everything that does not equal to "CCC=123" to be changed to "CCC=AAA"

So the result is:

CCC=123
CCC=AAA
CCC=AAA
CCC=123
CCC=AAA

How to do it in regex?

If I want everything that is equal to "CCC=123" to be changed to "CC开发者_JS百科C=AAA", it is easy to implement:

(AAA[ \t]*=)(123)


You can use a negative lookahead:

public static void main(String[] args) 
{

    String foo = "CCC=123 CCC=DDD CCC=EEE";
    Pattern p = Pattern.compile("(CCC=(?!123).{3})");
    Matcher m = p.matcher(foo);
    String result = m.replaceAll("CCC=AAA");

    System.out.println(result);

}

output:

CCC=123 CCC=AAA CCC=AAA

These are zero-width, non capturing, which is why you have to then add the .{3} to capture the non-matching characters to be replaced.


s = s.replaceAll("(?m)^CCC=(?!123$).*$", "CCC=AAA");

(?m) activates MULTILINE mode, which allows ^ and $ to match the beginning and and end of lines, respectively. The $ in the lookahead makes sure you don't skip something that matches only partially, like CCC=12345. The $ at the very end isn't really necessary, since the .* will consume the rest of the line in any case, but it helps communicate your intent.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号