简体   繁体   English

正则表达式匹配所有单词,但以特殊字符开头和结尾的单词除外

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

I'm struggling with a regex for Javascript. 我正在为Java正则表达式苦苦挣扎。

Here is a string from which I want to match all words but the one prefixed by \\+\\s and suffixed by \\s\\+ : 这是一个我想从中匹配所有单词的字符串,除了以\\ + \\ s为前缀并且以\\ s \\ +为后缀的单词:

this-is my + crappy + example 这是我+ cr脚+的例子

The regex should match : 正则表达式应匹配:

this-is my + crappy + example 这是 + cr脚+的例子

match 1: this-is 匹配1:这是

match 2: my 比赛2:我的

match 3: example 匹配3:示例

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. 从索引1获取匹配的组。

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

Live DEMO 现场演示

MATCH 1    this-is
MATCH 2    my
MATCH 3    example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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