I am new to regex and I have a confusing problem with regards to this scenario where I have a list of items with their weight and unit. I need to abbreviate the item and the weight however my regex broke when there is a negative number. Here is my current regex:
[.0-9] -\.?[0-9.]*
And here is my example case that is working
Lenovo Legion 5-15 lbs
I was able to match 5-15 and that is correct however when I have a value like
DELL XPS -2 lbs
My regex broke. How can I modify my regex to accommodate the negative value?
CodePudding user response:
You can use
-?\d (?:\.\d )?(?:-\d (?:\.\d )?)?
See the regex demo
Details:
-?
- an optional-
\d (?:\.\d )?
- one or more digits and then an optional occurrence of a.
and one or more digits(?:-\d (?:\.\d )?)?
- an optional occurrence of-
- a hyphen\d (?:\.\d )?
- one or more digits and then an optional occurrence of a.
and one or more digits