8 ms·
This highlights a way I constantly see people misuse regex: they aren’t specific enough. You weren’t bitten by Unicode, you were bitten by lazy and unprincipled
by stouset 2y ago
This highlights a way I constantly see people misuse regex: they aren’t specific enough. You weren’t bitten by Unicode, you were bitten by lazy and unprincipled parsing. Explicitly and strictly parse every character.
For here, assuming you already have only have the numeric value as a token, the regex should look like
/ ^ -? [0-9]+ ( \. [0-9]+ )? $ /x
or something similar. Match the beginning and end of the string and everything inbetween: an optional hyphen, any number of digits, and an optional decimal conponent. Feel free to adjust the details to match your spec, but any unexpected character will fail to parse.
- bregma 2y agoThat should be an optional minus sign, not an optional hyphen. Also, the radix character is locale-dependent so your should use a character class for it.
- nine_k 2y agoLocale-dependent parsing is a bit more complicated. For instance, you likely want to accept locale-specific numerals, and any of 77 ٧ ৭ 七 match the \d character class and mean "seven", but you likely don't want to accept a string as a valid number if different types of digits are mixed together. Also, 1,23,456.78 is fine in an Indian locale, but likely is a typo in the en_US or en_UK locales.
- IsTom 2y ago> your should use a character class That depends on locale. Is "1,222" 1222 or 1.222?
- account42 2y agoBut it definitely should not be the global process locale if you are parsing something that doesn't originate from the user's environment (and even then using something fixed like en_US or the saner en_DK unless a locale is explicitly requirested for the invocation makes sense).
- stouset 2y agoSure, the details depend on the exact format you're trying to parse. But the point is that you should strictly and explicitly match every component of the string.