Sanjay Sanjay - 6 months ago 27
PHP Question

Regular Expression to extract numbers from string with special characters

I have string like

8.123.351 (Some text here)

I have used the Regex


to take value "8.123.351" from string. It is working for the string given above.

But it is not working when the string without "." for example "179 (Some text here)".
I modified Regex to match this value also, but no success.

So can anyone suggest me the Regex to get numbers from strings like:

  1. 8.123.351 (Some text here)

  2. 179 (Some text here)

  3. 179.123 (Some text here)

  4. 179.1 (Some text here)


You are not very clear. I make some assumptions to create a pattern.

  1. The numbers are at the start of the string
  2. There is at least 1 digit and at most 3 digits before there is a dot

Now we create your expression

  1. Match 1 to 3 digits at the start of the row

  2. There is optionally (the ? after the group) a dot and one to three more digits

  3. This part with the dot can be repeated 0 or more times (replace the ? with a *)


    See it here on Regexr

If you want to read some basics about regular expressions, I wrote a blog post about that.