开发者

Use regex match or split to look for specific string

开发者 https://www.devze.com 2023-03-23 08:29 出处:网络
I have the following string : \'user-status status-avail left top-pos\'. I\'d like to lookup this string searching for \'status-something\' where something can have different forms like \'busy\' \'not

I have the following string : 'user-status status-avail left top-pos'.

I'd like to lookup this string searching for 'status-something' where something can have different forms like 'busy' 'not_busy' and return this specific string. How should I write my regex and should I use split or match for this task ?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消