0

I'm having problems with the following Regex:

I login with (CORRECT|INCORRECT (username|password|username and password)) credentials

Basically, what I want it to match is the following 4 strings only (which it does):

  1. I login with CORRECT credentials
  2. I login with INCORRECT username credentials
  3. I login with INCORRECT password credentials
  4. I login with INCORRECT username and password credentials

However, the match groups are as follows:

  1. 1: CORRECT 2:
  2. 1: INCORRECT username 2: username
  3. 1: INCORRECT password 2: password
  4. 1: INCORRECT username and password 2: username and password

I want the match groups as follows:

  1. 1: CORRECT
  2. 1: INCORRECT 2: username
  3. 1: INCORRECT 2: password
  4. 1: INCORRECT 2: username and password
2
  • 2
    Try (?| for the outer group so that it numbers subpatterns based on which option is matched. Commented Sep 6, 2016 at 17:24
  • What engine is it you're using? Commented Sep 6, 2016 at 18:04

2 Answers 2

1

If you can use an engine that supports Branch Reset it can be done like this

I login with (?|(CORRECT)()|(INCORRECT) (username(?: and password)?|password)) credentials

The group numbering is reset on each alternation in the branch reset group:

 I [ ] login [ ] with [ ] 
 (?|                           # Branch reset
      ( CORRECT )                   # (1)
      ( )                           # (2)
   |                              # or,
      ( INCORRECT )                 # (1)
      [ ] 
      (                             # (2 start)
           username 
           (?: [ ] and [ ] password )?
        |  
           password
      )                             # (2 end)
 )                             # End branch reset
 [ ] credentials

Or, if branch reset is unavailable use this

I login with (?:(CORRECT)|(INCORRECT) (username|password|username and password)) credentials

What this does is capture correct/incorrect in separate groups, then
if group 2 matched, group 3 is valid.
It still matches the exact same strings.

 I[ ]login[ ]with[ ]
 (?:
      ( CORRECT )                   # (1)
   |  ( INCORRECT )                 # (2)
      [ ]
      ( username | password | username[ ]and[ ]password )  # (3)
 )
 [ ]credentials
Sign up to request clarification or add additional context in comments.

Comments

0

You don't need nested groups, you can use this regex with fixed first group and an optional 2nd group:

I login with ((?:IN)?CORRECT) (?:(username|password|username and password) )?credentials

RegEx Demo

1 Comment

The problem is if the OP requires only CORRECT credentials, because that's how he set up his regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.