简体   繁体   中英

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

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' ]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM