开发者

Regular expression string search in Java

I know this can be done in many ways but im curious as to what the regex would be to pick out all strings not containing a particular substring, say GDA from strings like GADSA, GDSARTCC, , 开发者_JAVA技巧THGDAERY.


you can do negative lookaround

"^((?!GAD).)*$"


You don't need a regex. Just use string.contains("GDA") to see if a string contains a particular substring. It will return false if it doesn't.


If your input is one long string then you have to decide how you define a substring. If it's separated by spaces then:

String[] split = mylongstr.split(" ");
for (String s : split) {
  if (!s.contains("GDA")) {
    // do whatever
  }
}


String regex = ".*GDA.*";

List<String> testStrings = populateStrings();

for (String s : testStrings)
{
    if (!s.matches(regex))
        System.out.println("String " + s + " does not match " + regex);
}


Give this a shot:

java.util.regex.Pattern p = java.util.regex.Pattern.compile("(?!\\w*GDA\\w*)\\b\\w+\\b");
java.util.regex.Matcher m = p.matcher("GADSA, GDSARTCC, , THGDAERY");
while (m.find()) {
    System.out.println("Found: " + m.group());
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜