Reputation: 1869
I think this is called negative lookahead (new to regex) in any event not getting the results I want. I am trying to use it to disqualify or qualify an entire group
(?(?!The|Cross)(\w+ )Street)
So I want to capture the STREET group when it is Main Street or Bank Street but not The Street or Cross Street.
What I get for the String 'The Street' is
likewise for 'Cross Street' I get
What I am looking for is no match i.e. 'Your pattern does not matach the substring'
Is there a way to use negative lookahead in this manner? In other words AnyWord Street matches my pattern, The Street and Cross Street do not and return zero matches and no value for the label.
Upvotes: 0
Views: 141
Reputation: 122
Your requirement is ambiguous. You have written "I want to capture the STREET group when it is Main Street or Bank Street but not The Street or Cross Street".
This condition can be reduced to either
These variants are different from on another.
But your code example tends to the 2nd alternative. That's why an answer below is for the 2nd choice.
Examples correspond to a Perl syntax:
/(?<!The|oss)\s+Street/
Explanation: in Perl lookbehind (?<=fixed-regexp) only works for regexps of fixed width. Therefore characters "Cr" from "Cross" were removed.
The weakening of regex from "Cross" to "oss" can be avoided as follows:
/(?<!The)(?<!Cross)\s+Street/
Upvotes: 0
Reputation: 369434
Using word boundary (\b
) will give you what you want.
Javascript example:
/(?!The|Cross)(\b\w+ )Street/.test('Main Street')
// => true
/(?!The|Cross)(\b\w+ )Street/.test('Bank Street')
// => true
/(?!The|Cross)(\b\w+ )Street/.test('The Street')
// => false
/(?!The|Cross)(\b\w+ )Street/.test('Cross Street')
// => false
Upvotes: 1