J nui
J nui

Reputation: 190

Regex can't seem to quite capture decimal point

I want to capture the real number that follows the characters "FM" The regex I have does it in most situations except when there is a decimal point directly after the characters FM, e.g FM.3 it only captures the digit 3 and not the decimal point.

here's my regex

FM\W?(\.{0,1}\d?\.?\d?)?

here are the strings to test

MC1 FM1.2 MC2,
 FM.3,
FM 3,
FM.3,
FM 2 MC1,
FM 0.2 P1 MC1,
FM .3 ,

here's a demo https://regex101.com/r/ZBVpuS/2 It's much easier to see the issue at this link

Upvotes: 0

Views: 44

Answers (2)

ctwheels
ctwheels

Reputation: 22837

See regex in use here

FM\s*(\.\d+|\d+(?:\.\d+)?)
  • FM Match this literally
  • \s* Match any number of whitespace charactesr
  • (\.\d+|\d+(?:\.\d+)?) Capture either of the following options into capture group 1
    • \.\d+ Match . followed by one or more digits
    • \d+(?:\.\d+)? Match one or more digits, optionally followed by a dot and one or more digits. If you want to allow a match on a number such as 1. where there's no digit after the decimal point, you can change \.\d+ to \.\d*

Upvotes: 1

Andy G
Andy G

Reputation: 19367

You don't need \W which will swallow the dot (a non-word character):

FM\s*(\.?\d?\.?\d?)?

The \s* outside of the capture group will drop any whitespace after FM.

Upvotes: 1

Related Questions