Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match no groups, 1st group OR 2nd group but not both. Something like 'NAND'

Tags:

python

regex

I can't figure out how to write regex that matches these:

  • everyone hi
  • hi everyone
  • hi

But not this:

  • everyone hi everyone

The regex (?:everyone )?hi(?: everyone)? will match the latter as well (which is not what I want). How to make such a regex? Or is it just not possible? I couldn't do enough research because I couldn't express the problem in correct words. Sorry if I posted a duplicate

like image 270
Drdilyor Avatar asked Jan 25 '23 09:01

Drdilyor


2 Answers

Here is a brute force alternation way to get this done:

^(?:everyone +hi|hi(?: +everyone)?)$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start a non-capture group
    • everyone: Match everyone:
    • +hi: Match 1+ spaces followed by hi
    • |: OR
    • hi: Match hi:
  • (?: +everyone)?: Optionally match 1+ spaces followed by everyone
  • ): End non-capture group
  • $: End
like image 154
anubhava Avatar answered Jan 27 '23 00:01

anubhava


You could explicitly make a regex for each case (the first will capture two), utilizing beginning and end of line tokens

(^hi( everyone)?$) (^everyone hi$)

like image 31
Aliisa Roe Avatar answered Jan 26 '23 22:01

Aliisa Roe