1

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks QTax! What does the ?: do?
@Dan Baylis that signifies a non-capturing group (meaning the group will not be available as a backreference)
2

\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/

1 Comment

@Dan Baylis Good to hear. If you aren't using the value, it might be worth it to make it a non-capturing group as in Qtax's example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.