Home > database >  Regex match at least two or one word
Regex match at least two or one word

Time:07-11

I'd like to create regex to find at least two words or one

For ex

I have this phrases

I will buy a car
I will buy a horse
I will buy an electronic device
I will buy chip electronic
a device electronic will buy by my uncle

And I'm using (buy|eletronic)(?:\W \w ){1,7}?\W (buy|eletronic)

DEMO: https://regex101.com/r/g1IUXm/1

I'd like to find

I will buy an electronic device
I will buy chip electronic
a device electronic will buy by my uncle

and if I used just buy I'd like to find all phrases

CodePudding user response:

For the first pattern, you can use a backreference if that is supported with a negative lookahead (note that there is also a typo in your pattern eletronic missing a c char)

For the example I have omitted matching a newline for \W

\b(buy|electronic)(?:[^\w\n] \w ){1,7}?[^\w\n] (?!\1)(?:buy|electronic)\b

Regex demo

If you want to match all lines with the word buy:

.*\bbuy\b.*

CodePudding user response:

Use this regex if you want to match the whole line that contains buy or eletronic before buy or eletronic.

^.*?(?:buy|eletronic).*?(?:buy|electronic).*?$

Regex demo: https://regex101.com/r/FXtByF/1

CodePudding user response:

The way to use 'contains' in regex is to use look aheads.

You can use this regex:

^(?=.*buy)(?=.*electronic).*

Use global and multiline flags.

Explanation:

^ - match from start of line

(?=.*buy) - look ahead for any character zero or more times followed by buy

(?=.*electronic) - look ahead for any character zero or more times followed by electronic

.* - match rest of line

If you only want one word match, you can simply drop the other.

If you want to catch the words you can surround them with parentheses to create groups.

  • Related