user2758141
user2758141

Reputation:

Javascript RegExp - how to match X only when A is before X and B is after X

Given string "AXB", I would like to match X only when A is before X and B is after X. However I don't want A or B in my returned match.

I understand that for B it can be done this way: /X(?=B)/ but I am not sure if there is similar way to do so for A (before the match)?

Thank you.

Upvotes: 1

Views: 53

Answers (2)

hwnd
hwnd

Reputation: 70732

Use a capturing group to capture the value and then refer to group #1 to access your match.

/A(X)B/

Example:

console.log('AXB'.match(/A(X)B/)[1]); //=> 'X'

Upvotes: 2

zx81
zx81

Reputation: 41848

Like this:

var the_captures = []; 
var yourString = 'your_test_string'
var myregex = /A(X)B/g;
var thematch = myregex.exec(yourString);
while (thematch != null) {
    // add it to array of captures
    the_captures.push(thematch[1]);
    document.write(thematch[1],"<br />");    
    // match the next one
    thematch = myregex.exec(yourString);
}

Explanation

  • A matches the literal A
  • (X) matches X and captures it to Group 1
  • B matches B
  • The script returns Group 1: thematch[1]

In Other Languages

JavaScript doesn't have lookarounds or \K. In languages that support these, you can directly match X without capture groups:

  • A\KX(?=B) (using lokahead and \K, which tells the engine to drop what was matched so far from the final match it returns)
  • (?<=A)X(?=B) (using lookbehind and lookahead assertions)

Upvotes: 1

Related Questions