正则表达式匹配指定数字:如何避免部分匹配实现完全匹配
Got it, let's sort out this regex problem you're facing! The issue with your current pattern /4|46|64/g is that it doesn't enforce exact match boundaries—so it'll pick up the "4" inside "48" because it just looks for those digit sequences anywhere, even as part of a longer number.
Here are two solid solutions to get the exact matches you need:
Use word boundaries (
\b): This works great if your target numbers are treated as "words" (surrounded by non-word characters like spaces, letters, or punctuation). The updated regex would be:/\b(4|46|64)\b/gThe
\bmarkers ensure that the matched digits are standalone—so it won't latch onto the "4" in "48" or "64" in "649", but will correctly match "4", "46", "64", or something like "foo 46 bar".Use numeric boundary assertions: If you need stricter control (for example, if numbers might be adjacent to non-word characters like symbols), use negative lookarounds to make sure there aren't other digits before or after your target:
/(?<!\d)(4|46|64)(?!\d)/g(?<!\d)checks that there's no digit immediately before the match, and(?!\d)checks for no digit immediately after. This prevents partial matches in any context, even if the number is next to symbols like "$4" or "64!".
If you're trying to match cases where the entire string is exactly one of these numbers (not just a substring), use start and end anchors instead:
/^(4|46|64)$/
This will only return a match if the input is exactly "4", "46", or "64" with nothing else before or after.
内容的提问来源于stack exchange,提问作者Ben Osborne

