2

I'm trying to wrap my mind around regex for the first time.

For the string

I want you to MATCH THIS, you bastard regex, but also MATCH X THIS and yeah,
MATCH X X X THIS too.

Basically, a starting pattern, an end pattern and an arbitrary number of a pattern inbetween.

So I'd like a myregex.exec string to successively return

["MATCH", "THIS"]
["MATCH", "X", "THIS"]
["MATCH", "X", "X", "X", "THIS"]

I've tried variations of this

/(MATCH)\s+(X)?\s+(THIS)/

but no cigar...

3
  • So do you want to match all the white space delimitted upper case words? Commented Jul 15, 2015 at 8:27
  • This is partially answered in stackoverflow.com/questions/5018487/… - see Tim Picker's comment. Short answer: in some flavours of Regex you can ask for multiple captures of the same group. But not in javascript. Commented Jul 15, 2015 at 8:29
  • Having said that - you can group all of it in one group and then split. Commented Jul 15, 2015 at 8:48

2 Answers 2

2

You can use the regular expression to match the entire expression:

/MATCH\s+(?:X\s+)*THIS/g

To get it into an array of terms/words you can then use String.split() like this:

var out = document.getElementById( "out" );

function parse( string ){
  var re = /MATCH\s+(?:X\s+)*THIS/g;
  var matches = (string.match( re ) || [])
                  .map( function(m){ return m.split( /\s+/ ); } );
  out.innerHTML = JSON.stringify( matches );
}

parse( document.getElementById( "in" ).value );
textarea { width: 100%; }
<textarea id="in" onchange="parse( this.value )">I want you to MATCH THIS, you bad regex, but also MATCH X THIS and yeah, MATCH X X X THIS too.</textarea>
<p id="out"/>

Sign up to request clarification or add additional context in comments.

Comments

1

Try putting the \s+ into the optional group with *:

/(MATCH)\s+(?:(X)\s)*(THIS)/g

Note the g modifier to get all matches.

2 Comments

(?:(X)) would never have done that. A capture group in a non-capture group ... weird. Doesn't work for MATCH X X X THIS, but apparently that don't work in JavaScript...
Will match multiple Xs but will only ever return a single X as a capture group using RegExp.exec() - and for MATCH THIS it will return an empty capture group for the Xs.

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.