Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression - match word only once in line

Case:

  1. ehello goodbye hellot hello goodbye
  2. ehello goodbye hello hello goodbye

I want to match line 1 (only has 'hello' once!) DO NOT want to match line 2 (contains 'hello' more than once)

Tried using negative look ahead look behind and what not... without any real success..

like image 457
user1135229 Avatar asked Jan 06 '12 21:01

user1135229


2 Answers

A simple option is this (using the multiline flag and not dot-all):

^(?!.*\bhello\b.*\bhello\b).*\bhello\b.*$

First, check you don't have 'hello' twice, and then check you have it at least once.
There are other ways to check for the same thing, but I think this one is pretty simple.

Of course, you can simple match for \bhello\b and count the number of matches...

like image 166
Kobi Avatar answered Oct 21 '22 00:10

Kobi


A generic regex would be:

^(?:\b(\w+)\b\W*(?!.*?\b\1\b))*\z

Altho it could be cleaner to invert the result of this match:

\b(\w+)\b(?=.*?\b\1\b)

This works by matching a word and capturing it, then making sure with a lookahead and a backreference that it does/not follow anywhere in the string.

like image 23
Qtax Avatar answered Oct 21 '22 00:10

Qtax