Regular expression with if condition

I am new to regex. I am trying to build a regex that the first three characters must be alphabets, and the rest of the string can be any character. If the part of the line after the first three characters contains, then this part shall begin and end with the character ".

I was able to build ^ [az] {3}, but was stuck in a conditional statement.

Can this be done in one expression?

+4
source share
5 answers

In most regex options, you can use simple scans to make sure some text is present or not somewhere to the right of your current locations, and |you can check alternatives with the rotation operator .

So, we basically have 2 alternatives: is there &somewhere in the line after the first 3 alphabets or not. So we can use

^[A-Za-z]{3}(?:(?=.*&)".*"|(?!.*&).*)$

Watch the regex demo

More details

  • ^ - beginning of line
  • [A-Za-z]{3} - 3 alphabets
  • (?:(?=.*&)".*"|(?!.*&).*) - Any of two alternatives:
    • (?=.*&)".*"- if there is &somewhere in the line ( (?=.*&)) matches ", then any characters are 0+, and then"
    • | - or
    • (?!.*&).*- if there is no &( (?!.*&)) in the string , just match any 0+ characters with ...
  • $ - end of line.

PCRE, .NET, . PCRE:

^[A-Za-z]{3}(?(?=.*&)".*"|.*)$
            ^^^^^^^^^^^^^^^^^

(?(?=.*&)".*"|.*) :

  • (?(?=.*&) - & 0+...
  • ".*" - "anything here" -
  • | - , &
  • .* - 0+ (.. 3 ).
+3

| , , , .

^[a-z]{3}([^&]*$|".*"$)

, , ,

+1

, , , "" regex. :

\d{3}(\".*\"|[^&]*)

P.S. . : https://regex101.com/

0

, "", , . ( . Wiktor, .)

- :

^[a-z]{3}([^&]*|\..*\.)$

: " (&) , (.).

0

The expression itself will depend on the regexp parser you will be using. If you use Python, shell, vim, boost, etc., the same character can have different meanings.

I would try the following:

$ echo 'abc"&def"' | grep -E "^[a-zA-Z]{3}(\".*\&.*\"|[^&]*)"
abc"&def"
0
source

Source: https://habr.com/ru/post/1652968/


All Articles