Reputation: 151
I am looking to make a regex that will parse all floats in a given string. The thing is I need to ignore a special case; floats that are preceded by a /
The regex I currently have works okay, but it doesn't ignore the full float just the number after the /
(?<!/)[-]?[0-9]*\.?[0-9]+
Below are a few samples:
Thanks in advance
Upvotes: 2
Views: 164
Reputation: 70732
The Lookbehind excluding (/
) is not enough here, it's tricky but you need to exclude (0-9
, .
, -
) along with (/
) followed by a space in order to match the floats you specified.
(?<![0-9/.-]|/ )-?[0-9]*\.?[0-9]+
Another way to grab what you want would be to match the context you don't want. After matching the unwanted context, place what you want matched inside a capturing group and access that group for your matches.
/\s*\S+|(-?[0-9]*\.?[0-9]+)
Upvotes: 2
Reputation: 3175
This is a rather good Regex
question in my opinion. Assuming you want to do a replace
on any float
number that IS NOT preceded by a /
the following will work. This is the opposite of what your original regex
did, but it is probably easier to implement and is easier to read.
Regex
(?:[a-z]*|\/.*)
Test Data
1.25 some text /1.10 some more text
1 some different text
1.25 some text .012 some more text
-1.25 some text
/1.25
/you missed one 1.10
My Java
is rusty, but an example usage would be:
str = str.replaceAll("(?:[a-z]*|\/.*)", "");
Upvotes: 0