简体   繁体   English

从括号内获取整数

[英]Get integer from inside parentheses

I have a string where I'm trying to grab the integer inside. 我有一个字符串,我试图抓住内部的整数。 The string looks like: 字符串看起来像:

"(2) This is a string"

I need to grap that 2 . 我需要抓住那个2 but it could be any number so I tried: 但它可以是任何数字,所以我试过:

 var str = "(2) this is a string";
 var patt = /\(\d\)/;

 var num = str.match(patt);

This doesn't return the correct answer. 这不会返回正确答案。 Should I do a split on the () or is there a better regexp? 我应该对()进行拆分还是有更好的正则表达式?

var str = "(2) this is a string";
var patt = /\((\d)\)/;

var num = str.match(patt)[1];

2 things. 2件事。 When you want to capture a segment form a matched string, you use () to note that. 如果要从匹配的字符串中捕获段,可以使用()来注明。 So I just wrapped the \\d in parens to capture it. 所以,我刚刚结束了\\d在括号捕捉到它。

Second, in order to access the captured segments, you must drill into the returned array. 其次,为了访问捕获的段,您必须深入查看返回的数组。 the match method will return an array where the first item is the entire matched string, and the second item is any matched capture groups. match方法将返回一个数组,其中第一项是整个匹配的字符串,第二项是任何匹配的捕获组。 So use [1] to fetch the first capture group (second item in array) 所以用[1]来获取第一个捕获组(数组中的第二项)

var str = "(2) this is a string";
var patt = /\((\d+)\)/;
alert(str.match(patt)[1]);

This works! 这有效!

Why it works. 为什么会这样。 Because inside the (()) mayhem there's also a capture which populates the [1] elements in the matches array. 因为在(())混乱中,还有一个捕获,它填充匹配数组中的[1]元素。

Use this. 用这个。 doesnt matter how many parenthesis 没有多少括号

var str = "(2) this is a string";
var patt = /\(\d\)/;

var num = str.match(patt)[0].replace("(", "").replace(")","")

This should work 这应该工作

 var str = "(2) this is a string";
var a =  /\([\d]*\)/g.exec(str)[0];
 var num =  a.substring(1, a.length-1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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