Nicolas Forney
Nicolas Forney

Reputation: 888

Regex to match all words but the one beginning and ending with special chars

I'm struggling with a regex for Javascript.

Here is a string from which I want to match all words but the one prefixed by \+\s and suffixed by \s\+ :

this-is my + crappy + example

The regex should match :

this-is my + crappy + example

match 1: this-is

match 2: my

match 3: example

Upvotes: 2

Views: 60

Answers (2)

Braj
Braj

Reputation: 46841

As per desired output. Get the matched group from index 1.

([\w-]+)|\+\s\w+\s\+

Live DEMO

MATCH 1    this-is
MATCH 2    my
MATCH 3    example

Upvotes: 1

hwnd
hwnd

Reputation: 70732

You can use the alternation operator in context placing what you want to exclude on the left, ( saying throw this away, it's garbage ) and place what you want to match in a capturing group on the right side.

\+[^+]+\+|([\w-]+)

Example:

var re = /\+[^+]+\+|([\w-]+)/g,
    s  = "this-is my + crappy + example",
    match,
    results = [];

while (match = re.exec(s)) {
   results.push(match[1]);
}

console.log(results.filter(Boolean)) //=> [ 'this-is', 'my', 'example' ]

Alternatively, you could replace between the + characters and then match your words.

var s = 'this-is my + crappy + example',
    r = s.replace(/\+[^+]*\+/g, '').match(/[\w-]+/g)

console.log(r) //=> [ 'this-is', 'my', 'example' ]

Upvotes: 2

Related Questions