正则表达式匹配字符串的开头并捕获最后一部分

时间:2022-05-19 21:44:14

I have the following set of strings

我有以下字符串集

big-div button-green
big-div button-red
big-div button-yellow

and I'd like to get the following result

我想得到以下结果

green
red
yellow

I managed to get this far /\sbutton-[^\s]*/gi but matches the whole string as in button-yellow

我设法得到这个远/ \ sbutton - [^ \ s] * / gi但匹配整个字符串,如按钮黄色

Thanks in advance!

提前致谢!

3 个解决方案

#1


1  

Put a capturing group around [^\s]* and you can access that as the first capturing group.

在[^ \ s] *周围放置一个捕获组,您可以将其作为第一个捕获组进行访问。

Alternatively, I'd write that as...

另外,我会把它写成......

var match = (str.match(/\sbutton-(\S*)/gi) || [])[1];

This will give you the match, or undefined if it couldn't match anything.

这将为您提供匹配,如果无法匹配,则为undefined。

If str is a class too, I'd swap the boundaries for (?:^|\s) and (?:$|\s) or otherwise match on \s and wrap the matching string with spaces.

如果str也是一个类,我会交换(?:^ | \ s)和(?:$ | \ s)的边界,或者在\ s上匹配,并用空格包装匹配的字符串。

#2


1  

str.match(/\sbutton-([^\s]*)/i)[1]

#3


1  

The answer is in the title: just create a capture group:

答案在标题中:只需创建一个捕获组:

/\sbutton([^\s]+)$/i

and get the first element of the returned matches array, that'll contain only those chars you're interested in

并获取返回的匹配数组的第一个元素,它只包含您感兴趣的那些字符

#1


1  

Put a capturing group around [^\s]* and you can access that as the first capturing group.

在[^ \ s] *周围放置一个捕获组,您可以将其作为第一个捕获组进行访问。

Alternatively, I'd write that as...

另外,我会把它写成......

var match = (str.match(/\sbutton-(\S*)/gi) || [])[1];

This will give you the match, or undefined if it couldn't match anything.

这将为您提供匹配,如果无法匹配,则为undefined。

If str is a class too, I'd swap the boundaries for (?:^|\s) and (?:$|\s) or otherwise match on \s and wrap the matching string with spaces.

如果str也是一个类,我会交换(?:^ | \ s)和(?:$ | \ s)的边界,或者在\ s上匹配,并用空格包装匹配的字符串。

#2


1  

str.match(/\sbutton-([^\s]*)/i)[1]

#3


1  

The answer is in the title: just create a capture group:

答案在标题中:只需创建一个捕获组:

/\sbutton([^\s]+)$/i

and get the first element of the returned matches array, that'll contain only those chars you're interested in

并获取返回的匹配数组的第一个元素,它只包含您感兴趣的那些字符