javascript - How to get the content in parentheses using regular expressions in js?
滿天的星座2017-05-19 10:40:53
0
6
716
var str="deleteChild(236737)"; For example, get the number in parentheses 236737 Others are not required. How to write regular js. js array is too troublesome. Because the number in the parentheses will change.
Use d+ to indicate any whole number. In order to match the content at a special location, the concept of group in regular expressions is also used (shown in regular expressions as being enclosed by a pair of parentheses).
The shortcut way of expressing JavaScript regular expression is to enclose it with "/", for example /正则表达式内容/, it has an exec method, and the incoming parameter is the string to be checked. The execution result of the exec method returns an array or null value (when there is no content in str that matches the regular expression).
If the regular expression contains group and the content is matched, then in the returned result array, the text content represented by group will appear in the second array element and subsequent array elements of the result array (when the regular expression contains When containing multiple groups).
var str = "deleteChild(236737)";
var result = /\((\d+)\)/.exec(str);
if(result.length > 1) { //加这个判断是以防字符串中没有匹配的内容,那么result[1]会抛错!
console.log("您想要的结果是:" +result[1]); //输出 236737。
} else {
console.log("字符串中没有符合条件的数字");
}
I agree with the writing method on the 4th floor, it is so simple and convenient. Systematic learning of regular expressions, I highly recommend the regular expression front-end user manual | louis blog sf link: Regular expression front-end user manual-Louis chats about the front-end-SegmentFault The original content is super long , a very comprehensive summary.
Use
d+
to indicate any whole number. In order to match the content at a special location, the concept of group in regular expressions is also used (shown in regular expressions as being enclosed by a pair of parentheses).The shortcut way of expressing JavaScript regular expression is to enclose it with "/", for example
/正则表达式内容/
, it has an exec method, and the incoming parameter is the string to be checked.The execution result of the exec method returns an array or null value (when there is no content in str that matches the regular expression).
You can use the split method of string.
split() 方法用于把一个字符串分割成字符串数组。
My answer is also based on the principle of high-voted answers, but I personally think it may be easier to understand if I write it this way
I agree with the writing method on the 4th floor, it is so simple and convenient.
Systematic learning of regular expressions, I highly recommend the regular expression front-end user manual | louis blog
sf link: Regular expression front-end user manual-Louis chats about the front-end-SegmentFault
The original content is super long , a very comprehensive summary.