'Substitute integers and dots with regex [duplicate]
I have the following string and I need to substitute the numbers and dot with a star:
FOO_BAR_FOOBA_1_R:FOO_1.0
I tried the following but I just managed to substitute the last part, is there a way that I can do it with a single regex search? Or do I need to parse it twice?
Regex I tried is: (\d.\d)
. That one catches the last part but not the beginning.
I am using PHP so below is the code that I have so far:
$re = '/(\d.\d)/';
$str = 'FOO_BAR_FOOBA_1_R:FOO_1.0';
$subst = '*';
$result = preg_replace($re, $subst, $str);
echo "The result is".$result;
If I use \d
I get all the integers but not the dot plus multiple stars.
Solution 1:[1]
Your regex:
(\d.\d)
is looking for a number
, any non new line character
(.
is a special character in regex), and again a number
. The only place that occurs in your string is at the end. For a demo of this see: https://regex101.com/r/vHef6Q/2/
You could use:
\d+(\.\d+)?
to find any numbers with an optional decimal part.
Demo: https://regex101.com/r/vHef6Q/1/
Be careful with .
s in regexs. Also use quantifiers if multiple values are allowed. \d
is a single integer, for numbers greater than 9 you need a +
. This also is the answer to why you get multiple starts when you just use \d
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |