简体   繁体   中英

regular expression to match start character of string + space then digits like currency

How do I test a string that contains a character at the start then a space and whatever comes after that which could be an integer or float?

Example:

'$ 15'

'$ 15.95'

/\$\s[\d]*\.[\d]{2}|\$\s[\d]*[^.]/gm

$space(endless digits until)period and exactly-2digits
|OR
$space(endless digits-no periods)

 const rgx = /\$\s[\d]*\.[\d]{2}|\$\s[\d]*[^.]/gm; const str = `\$ 15.95 \$ 5 \$ 2.00 \$ 6.90 \$ 1101`; let matches = [...str.matchAll(rgx)].flat(); console.log(matches);

I think it could help you: ^\$ [+-]?[0-9]{1,}(\.[0-9]{1,}){0,1} , you can test it here: https://regex101.com/

  • ^\$ : start with a character
  • then add a space
  • [+-]? then add optional signs
  • [0-9]{1,} then add at less one digit
  • (\.[0-9]{1,}){0,1} then add a dot and at less one digit

You can use below regular expression:

. \d+(?:.\d+)?

Test it here: https://regex101.com/r/1oqIO8/1

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