Reputation: 2093
This must be an easy one, but I am trying to detect if the integers 28, 81, 379 or 380 exist in a string.
I was using this pattern:
pattern = /28|81|379|380/
But it also returns true for 381. So I need a modifier to make sure it is only looking for 81 specifically, and not 81 within a longer number. I know about the ^ and $ modifiers to check for the start and end, but I can't seem to figure out how to work those in to a pattern that is using the | symbol to check alternatives.
Regex is not my strength - hope you can help! - Dan
Upvotes: 1
Views: 150
Reputation: 33908
You can use something like:
/\b(?:28|81|379|380)\b/
With \b
matching at a "word barrier", so these numbers will not match if they are part of a word/other numbers.
If you want to match 28 in foo28
(part of a "word") then you can use:
/(?:^|\D)(?:28|81|379|380)(?:\D|$)/
\D
matches a not-number character.
Upvotes: 4
Reputation: 11744
\b
signifies a word boundary. You might use it as such:
/\b28\b|\b81\b|\b379\b|\b380\b/
Or as such:
/\b(28|81|379|380)\b/
Upvotes: 2