Use regex match or split to look for specific string
I have the following string : 'user-status status-avail left top-pos
'.
I've tried :
str.match(/status-([a-开发者_运维技巧z]+)/);
but I get :
["status-avail", "avail"]
in return, and not only 'status-avail'.
String.match() has two modes of operation
The string match()
method can be used two ways and its important to understand what it returns. If you set the 'g'
global flag, then the method returns an array of all the matches in a string and each element of the array contains one whole overall match of the regex. But if you DON'T set the 'g'
global flag, then the method only looks for the first match in the string and returns an array containing detailed information about that match. In this case, the first element (matches[0]
) contains the overall match and subsequent elements contain the contents of the capture groups within the regex (i.e. matches[1]
contains the contents of capture group 1, matches[2]
contains the contents of capture group 2, and so on).
The regex in the original post: (/status-([a-z]+)/
) does not have the 'g'
global flag set, so it is returning detailed info about the first match. And since there is one capture group, the returned array has two elements, the first element has the overall match and the second has the contents of the first and only capture group.
If you add the global flag, you will get an array of all of the whole matches in the string:
str.match(/status-([a-z]+)/g);
Or, (as other abswers have noted), you can remove the capturing parentheses from the regex, in which case the call to the match()
method will return an array containing only one element, which is the overal match:
str.match(/status-[a-z]+/);
the String.match()
is quite useful once you understand this behavior.
Remove the parentheses from your regex. (or just get the first item found)
var matches=str.match(/status-[_a-zA-Z]+/);
if(matches[0])
var statusSubstr=matches[0];
Try this. something
from you oroginal post with such RegExp could contain letter(with ignored cases) and '_'. statusSubStr
will contain what exactly you want. If str=user-status status-avail left top-pos
then statusSubStr=status-avail
. I hope it is helpfull.
精彩评论