Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

regex - 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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

^(?!.*hello.*hello).*hello.*$

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 hello and count the number of matches...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...