简体   繁体   中英

Javascript regexp (match after “:” symbol)

How to get all text following the symbol " : "?

I have tried:

'prop:bool*'.match(/:(.[a-z0-9]+)/ig)

But it returns [":bool"] not ["bool"] .

Update:

I need to use this inside the following expression:

'prop:bool*'.match(/^[a-z0-9]+|:.[a-z0-9]+|\*/ig);
So that the result becomes:
 ["prop", "bool", "*"] 

You could solve this by performing a positive lookbehind action.

'prop:bool*'.match(/^[a-z0-9]+|(?<=:).[a-z0-9]+|\\*/ig)

The positive lookbehind is the (?<=:) part of the regex and will here state a rule of must follow ':' .

The result should here be ["prop", "bool", "*"] .

Edit:

Original requirements were somewhat modified by original poster to return three groups of answers. My original code, returning one answer, was the following: 'prop:bool*'.match(/(?<=:).[a-z0-9]+/ig)

This is not a pure regex solution since it takes advantage of the String Object with its substring() method, as follows:

 var str = 'prop:bool*'; var match = str.match(/:(.[a-z0-9]+)/ig).pop().substring(1,str.length); console.log(match); 

When the match is successful, an array of one element will hold the value :bool . That result just needs to have the bool portion extracted. So, the element uses its pop() method to return the string value. The string in turn uses its substring() method to bypass the ':' and to extract the desired portion, namely bool .

 var [a,b,c] = 'prop:bool*'.match(/^([a-z0-9]+)|:(.[a-z0-9]+)|(\\*)/ig); console.log(a,b.substring(1,b.length),c); 

To return three groups of data, the code uses capture groups and trims off the colon by using the substring() method of b .

您可以简单地执行以下操作:

'prop:bool*'.match(/:(.[a-z0-9]+)/)[1]

如果您的整个字符串都是所显示的形式,则可以仅使用带有捕获组的正则表达式来获取每一个:

 console.log('prop:bool*'.match(/^([a-z0-9]+):(.[a-z0-9]+)(\\*)/i).slice(1)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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