简体   繁体   中英

Find numbers that are in parentheses using regular expression and Javascript

There is such line

let str = 'ds 1,2abc{3,4}dd'

I need to find numbers that will be included in {} without enclosing the brackets themselves.

For example (Assuming that regex is a per-defined regular expression) I want to write something like the following.

(str.match(regexp)).join('').split(',')

Which will produce a result like this => ['3','4']

and if I have only one char in brackets or char with comma I need to get next result

let str = 'ds 1,2abc{3,}dd'

(str.match(regexp)).join('').split(',') => ['3','']

At the moment, I have such a regular const regexp = (/\d+\,\d*|(?<=\{)\d+/ but it does not handle the case when there are more numbers in the string with a comma like 1,2

It seems you are actually trying to include an empty string in your resulting array. Maybe you could use:

 var str = 'ds 1,2abc{3,4}dd'; var res = str.split(/[{}]/)[1].split(","); console.log(res)


 var str = 'ds 1,2abc{3,}dd'; var res = str.split(/[{}]/)[1].split(","); console.log(res)

The usual workaround, when the number of open/close curly braces is matching and you need not pre-validate your input, you may simply use

str.match(/\d+(?:\.\d+)?(?=[^{}]*})/g)
str.match(/\d*\.?\d+(?=[^{}]*})/g)

Here, \d+(?:\.\d+)?(?=[^{}]*}) matches 1+ digits, followed with an optional sequence of a dot and 1+ digits followed with 0 or more chars other than { and } and then a } .

See this demo

In a more generic case, you may extract groups of numbers inside curly braces by matching curly braces with comma-separated numbers in them first. Then, you may extract the numbers from each match:

 const str = 'ds 1,2abc{3,4}dd{not this one 5,6} and {7,8.666,9,10.45}'; const rx = /{\d*\.?\d+(?:,\d*\.?\d+)*}/g; const results = str.match(rx).map(x => x.replace(/[{}]+/g,'').split(',')); console.log( results );

See the regex demo .

  • { - a { char
  • \d*\.?\d+ - 0 or more digits followed with an optional . and then 1+ digits
  • (?:,\d*\.?\d+)* - 0 or more repetitions of a comma followed with 0 or more digits followed with an optional . and then 1+ digits
  • } - a { char.

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.

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