Skip to content
Advertisement

Regext to match only ONE occurance of a pattern

How to write a regex that says that given pattern is present ONLY once?

for e.g.. if am searching for pattern ‘file’,

JavaScript

Advertisement

Answer

You could use a negative lookahead:

JavaScript

Test at regex101

You may apply the above regex in grep.

JavaScript

The negative lookahead assertion at ^ start (?!(?:.*?file){2}) looks ahead, if there’s not
2x ( .*? lazily any amount of any characters, followed by substring file ).
If this condition succeeds, it matches .*?file.* all string if it contains substring file.

For just matching the line the last greedy dot (to match any characters after file) is not required.

enter image description here

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement