Double Aspect Regular Expressions

Sorry for the confusing name, I could not come up with the correct wording. I'm trying to figure out if there is a regular expression way to match different lines, depending on whether the previous capture group was captured or not.

/th?u(e|r)sday/ 

This corresponds to tuesday , thursday , but also thuesday and tursday . Is there a way to indicate in a regular expression that the part should only match if the previous part was matched ... so I present a potential syntax, for example ... (?#:pattern) where # is the number from the capture group, and if the captured group is captured, then the template is included, otherwise it is skipped. Same model (!#:pattern) if group # th is not captured. This invented syntax should demonstrate what I'm trying to do. With this invented syntax, I could solve my problem above, like this ...

 /t(h)?u(!1:e)(?1:r)sday/ 

Is there such syntax in regex to achieve this type of link?

+4
source share
2 answers

This function exists in some regular expression implementations, and the regular expression from your example will be written as follows:

 /t(h)?u(?(1)r|e)sday/ 

Obviously, this is not a good example, since /t(hur|ue)sday/ equivalent and much shorter, but there are times when it is more useful.

Take a look at the second to last element in the table for this extended regex link page for more information on conventions here .

  • Syntax:

     (?(1)then|else) 
  • Description:

    If the first capturing group has been involved in the match attempt so far, the β€œthen” part must match to match the regular expression in general. If the first capture group did not participate in the match, the else part should match the overall regular expression match.

  • Example:

    (a)?(?(1)b|c) matches ab , first c and second c in babxcac

According to the same page, conditional expressions are supported by the JGsoft engine , Perl , PCRE and .NET framework .

+4
source

Why not just use a more specific clause?

 /t(hur|ue)sday/ 
+1
source

All Articles