简体   繁体   English

在Javascript中使用正则表达式仅检索匹配字符串的一部分

[英]Retrieve only a portion of a matched string using regex in Javascript

I've got a string like 我有一个字符串

foo (123) bar

I want to retrieve all numbers surrounded with the delimiters ( and ) . 我想检索用分隔符()包围的所有数字。

If I use varname.match(/\\([0-9]+\\)/) , my delimiters are included in the response, and I get "(123)" when what I really want is "123". 如果我使用varname.match(/\\([0-9]+\\)/) ,我的分隔符将包含在响应中,当我真正想要的是“123”时,我得到“(123)”。

How can I retrieve only a portion of the matched string without following it up with varname.replace() ? 如何在不使用varname.replace()情况下检索匹配字符串的一部分?

是的,使用捕获(非转义)的parens:

varname.match(/\(([0-9]+)\)/)[1]

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

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