user559142
user559142

Reputation: 12517

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, , THGDAERY.

Upvotes: 0

Views: 428

Answers (5)

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

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());
}

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342363

you can do negative lookaround

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

Upvotes: 2

mmorrisson
mmorrisson

Reputation: 541

String regex = ".*GDA.*";

List<String> testStrings = populateStrings();

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

Upvotes: 0

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

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
  }
}

Upvotes: 1

dogbane
dogbane

Reputation: 274612

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.

Upvotes: 2

Related Questions