Home > front end >  regular expression to match start character of string space then digits like currency
regular expression to match start character of string space then digits like currency

Time:02-05

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'

CodePudding user response:

/\$\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);

CodePudding user response:

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
  •  Tags:  
  • Related