What does this regex mean

I really need to know:

  • What does (?( ?
  • What does it mean ?: ?

The regular expression I'm trying to figure out is the following:

(note the above characters in the following regular expression)

 (?(?=and )(and )|(blah))(?:[1][9]|[2][0])[0-9][0-9] 
+6
source share
4 answers

(?(?=and )(and )|(blah)) pattern is used as if-then-else as (?(expression)yes|no) ie and will match if and there is else blah will be matched

(?:) is not an exciting group. Therefore, it will not be included in the group or will be used as a back link \ 1

So,

 (?(?=and )(and )|(blah))(?:[1][9]|[2][0])[0-9][0-9] 

will match

 and 1900 blah2000 and 2012 blah2013 

NOTE (all about groups)

This can be achieved using this regular expression (and |blah)(?:[1][9]|[2][0])[0-9][0-9] . The only thing that differs from this regular expression is the number of groups formed.

So my regex would form 1 group that would contain and or or blah

Your regular expression will not form groups. It forms a group only if it matches blah ..

+2
source

Here is a short link to some templates:

 . Any character except newline. \. A period (and so on for \*, \(, \\, etc.) ^ The start of the string. $ The end of the string. \d,\w,\s A digit, word character [A-Za-z0-9_], or whitespace. \D,\W,\S Anything except a digit, word character, or whitespace. [abc] Character a, b, or c. [az] a through z. [^abc] Any character except a, b, or c. aa|bb Either aa or bb. ? Zero or one of the preceding element. * Zero or more of the preceding element. + One or more of the preceding element. {n} Exactly n of the preceding element. {n,} n or more of the preceding element. {m,n} Between m and n of the preceding element. ??,*?,+?, {n}?, etc. Same as above, but as few as possible. (expr) Capture expr for use with \1, etc. (?:expr) Non-capturing group. (?=expr) Followed by expr. (?!expr) Not followed by expr. 

The expression (?(?=and )(and )|(blah)) is an if-else expression :)

Here you can test the expressions: Regexpal.com

+2
source
 (?:...) 

- This is not an exciting group . It works the same as (...) , but it does not create a backlink ( \1 , etc.) for subsequent reuse.

 (?(condition)true|else) 

is a conditional that tries to match a condition ; if it succeeds, it will try to match true ; if not, it will try to match else .

This is a rare regex construct because there aren't many use cases for it. In your case

 (?(?=and )(and )|(blah)) 

could be rewritten as

 (and |blah) 
+2
source

?: - not an exciting group. (?ifthen|else) used to build if, then expression.

You can read more about this here.

http://www.regular-expressions.info/conditional.html

0
source

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


All Articles