Nickpick
Nickpick

Reputation: 6597

Regex: exclude trailing .0 but include all strings

I have a number of floats/strings that look as follows: 12339.0 133339 159.0 dfkkei something 32439

Some of them have trailing .0. How can I show all the numbers without the trailing .0 as a regular repression, including the items that are not a number? I tried something like that, hoping it would exclude all .0 from the capture group, but it doesn't work: (.*)(:?.0)?

https://regex101.com/r/sC6jO2/1

Upvotes: 2

Views: 278

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

You may use a simpler regex:

\.0+$

And replace with an empty string, see regex demo.

The regex matches a . (\.) followed with 1 or more zeros (0+) up to the end of string ($).

If you plan to match two groups as in your initial attempt, use

^(.*?)(?:\.0+)?$

See this regex demo

Here,

  • ^ - start of string
  • (.*?) - Group 1 capturing any 0+ chars other than a newline, as few as possible (=lazily), up to a
  • (?:\.0+)? - optional sequence of . + one or more zeros
  • $ - at the end of the string.

Upvotes: 3

Related Questions