简体   繁体   English

Javascript正则表达式结束单词未找到

[英]Javascript regex ending word not found

In this regex , I need to match an ending word that starts with '(', ')' or ',' . 在这个正则表达式中 ,我需要匹配以'(', ')'','开头的结束词。

Regex : 正则表达式:

/[\(\),].*$/

For example, given the text (aaa,bbb)ccc I need to obtain )ccc . 例如,给定文本(aaa,bbb)ccc我需要获得)ccc Still, it returns the entire text. 仍然,它返回整个文本。 What's wrong with this regex? 这个正则表达式有什么问题?

You can use: 您可以使用:

'(aaa,bbb)ccc'.match(/[(),][^(),]+$/)
//=> [")ccc"]

[^(),]+ is negation pattern that matches any character but any listed in [^(),] . [^(),]+是与[^(),]列出的任何字符匹配的否定模式

Problem with [(),].*$ is that it matches very first ( in input and matches till end. [(),].*$是它首先匹配(在输入和匹配到结束。

You can also consider using capturing group while consuming all the characters up to the first ( , ) or , : 您也可以考虑使用捕获组,同时消耗的所有字符,直到达到第(),

.*([(),].*)$

.* will consume as many characters as it can, then any character in this character class [(),] , and then the rest of the characters up to the end. .*将消耗尽可能多的字符,然后消耗此字符类[(),]任何字符,然后是其他字符直到最后。

The )ccc value will be stored in Group 1: )ccc值将存储在第1组中:

 var re = /.*([(),].*)$/; var str = '(aaa,bbb)ccc'; if ((m = re.exec(str)) !== null) { document.getElementById("res").innerHTML = m[1]; } 
 <div id="res"/> 

试试这个正则表达式:

/[(,)][^(,)]*$/

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

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