1

I'm having trouble coming up with a regex to accept two possible values.

I would like to accept a % or a number and unit.

For example. Any percentage between 0% and 100% are acceptable. OR Any integer followed by a suffix. (10 AB, 78JB, 244 AB). Only possible suffixes are (AB, JB, RB, LB, IB)

Value must be one or the other (2% OR 10 AB);

I can do these individually with regex but don't know how to combine into one.

\d+\s?(AB|JB|RB|LB|IB)?
\d+\s?\%
4
  • 1
    Group the two regexes and use OR | to match either! Commented Feb 9, 2017 at 23:10
  • ah....duh....i was trying to share the digits part...but that approach works as well. Thx. Commented Feb 9, 2017 at 23:11
  • Are the suffixes to be matched as whole words? I.e. do you need to match 10 AB in 10 ABC? Try /\d+\s?(?:(?:AB|JB|RB|LB|IB)\b|%)/g Commented Feb 9, 2017 at 23:12
  • 1
    So simple \d+\s?(?:%|AB|JB|RB|LB|IB) combine and conquer.. Commented Feb 9, 2017 at 23:41

2 Answers 2

1

If you plan to "merge" the patterns so as to only repeat the \d+ part once, you may just include the % into the alternation group with letter suffxies:

/\d+\s?(?:AB|JB|RB|LB|IB|%)/g

(see the regex demo) unless you need to match the suffixes as whole words. In that case, you need to add a word boundary after the suffixes only, not after %:

/\d+\s?(?:(?:AB|JB|RB|LB|IB)\b|%)/g

See the regex demo

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

Comments

0

It seems like you can just add an OR statement between the two:

\d+\s?(AB|JB|RB|LB|IB)|\d+\s?\%

See it in action here. I removed a ? after the 'number unit'.

Comments

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.