using JavaScript and Regular Expressions, how can I get the first match of a number (positive or negative) within square brackets.
For example, how can I extract the number 232 in the following text: "Hello this is a number [232]"
You can use a capture group to pull the number out with something like:
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 []
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.