繁体   English   中英

从字符串中提取方括号内的数字

[英]Extract number within square brackets from string

使用JavaScript和正则表达式,如何获得方括号内数字(正数或负数)的第一个匹配项。

例如,如何提取以下文本中的数字232: “您好,这是一个数字[232]”

您可以使用捕获组将数字拉出,例如:

 let s = "Hello this is a number [232]" let t = "Hello [-100] this is a number " let u = "Hello [-232a] this [121] is a number " // doesn't match 232a let rx = /\\[(-?\\d+)\\]/ console.log(s.match(rx)[1]) console.log(t.match(rx)[1]) console.log(u.match(rx)[1]) 

const patter = /(?!\[)-?\d+(?=\])/g;
// will return only number without []

暂无
暂无

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

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