Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add an optional string or end the string with Regex?

I want to get all Strings that start with a "$"-sign followed by an integer, or have exactly two digits after the decimal point.
e.g. $7.26 and $48.49 and $17
but not $.49 and $192.9

That’s my regular expression so far: ^[$]\d+[.][0-9][0-9]

I want the marked part to be optional or the string has to end.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Also, how could I use [0-9]{2} instead of [0-9][0-9]?

>Solution :

Try this pattern: ^\$\d+(?:\.\d{2})?$

See Regex Demo

Explanation

  • ^: Start of the string.
  • \$: Match with the character $.
  • \d+: Match with one or more digits between 0-9.
  • (?:: Start of the non-captured group.
  • \.: Match with the dot character.
  • \d{2}: Match exactly two digits.
  • ): End of the group.
  • ?: Make everything in the group optional.
  • $: End of the string.

Note: the $ and . character in regex means respectively end of the string and everything, so if we want to capture exactly the $ character (not the end of the string) we should escape those characters.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading