Daniel
Daniel

Reputation: 1491

RegEx matching standalone string with dashes

I need to write a RegEx to match the "1-234-5678" string if there are no dash characters around it.

I have the following RegEx:

\b\d\-\d{3}\-\d{4}\b

Now this works fine and matches "1-234-5678" correctly in the strings below:

The RegEx also correctly NOT matches "1-234-5678" in the strings below:

But the problem is that it also matches in the following strings:

It's because \b matches before and after the dashes.

How can I eliminate matches if there's a dash in front or after the data?

Upvotes: 0

Views: 98

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174844

Use a negative lookbehind and negative lookahead to check whether the above mentioned format is not preceded and followed by a - symbol,

(?<!-)\b\d\-\d{3}\-\d{4}\b(?!-)

DEMO

Upvotes: 1

Related Questions