user2589299
user2589299

Reputation: 129

regex exp to detect only one occurrence of an "abc-xxx" pattern

Here are a list of strings

  1. abc-1234 hi hello~abc-3456 ok~abc-4456
  2. abc-1234
  3. abc-2356 hi~abc-1234 ok
  4. abc-1234 ok~abc-1234 hello
  5. abc-1234 ok~abc-1234 hello~abc-1456 ok ok

Need to write a regex pattern that will detect if abc-1234 is the only "abc-" pattern presentand match it. If abc-1234 is present along with another abc-xxxx pattern, we should not have a match. In other words, I need to write a regex pattern to match the occurrence of abc-1234 when it's the only abc- pattern present. Note that the abc pattern is always preceeded by '~'

So in the above cases, when we try to do a match between the regex pattern and the strings, we get the following results : 1. does not match 2. matches 3. does not match 4. matches 5. does not match

Can a regex expert help me here?

Thanks!

Upvotes: 3

Views: 1010

Answers (3)

Chris Charley
Chris Charley

Reputation: 6573

A solution in Perl using 2 regexes. It gets the count of all matches, abc-\d\d\d\d and compares that count to the count for abc-1234 matches.

print if  ( () = /abc-\d\d\d\d/g) ==  ( () = /abc-1234/g);

Upvotes: 0

perreal
perreal

Reputation: 97948

Using positive-negative lookeheads:

use strict; use warnings;
my @s = ('abc-1234 hi hello~abc-3456 ok~abc-4456',
    'abc-1234', 'abc-2356 hi~abc-1234 ok', 'abc-1234 ok~abc-1234 hello',
    'abc-1234 ok~abc-1234 hello~abc-1456 ok ok');

for my $s (@s) {
    if ($s !~ /^abc-(\d+)(?=.*~abc-(?!\1))/) {
        print "$s\n";
    }
}

Output

abc-1234
abc-1234 ok~abc-1234 hello

Upvotes: 3

Bohemian
Bohemian

Reputation: 425033

Use a negative look ahead anchored to start of input:

^(?!(.*abc-\d{4}){2}.*$)abc-\d{4}

Upvotes: 0

Related Questions