-3

How do I write a regular expression to match the following:

CONTEXT_84 = 

or

CONTEXT_5 = 
0

6 Answers 6

8

Try:

CONTEXT_\d{1,2} = 

Which means:

CONTEXT_\d{1,2} 

Match the characters “CONTEXT_” literally «CONTEXT_» Match a single digit 0..9 «\d{1,2}» Between one and 2 times, as many times as possible, giving back as needed (greedy) «{1,2}»

Created with RegexBuddy

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

2 Comments

+1 (assuming this is what the OP intended). Also RegexBuddy attempts to make a human readable explanation of the regex? That's kind of neat, I'll have to look at it.
Yeah - the explanation is exported from the "Create" Window of RegexBuddy - I found it very helpful when I was learning regex
7
CONTEXT_(84|5) = 

3 Comments

This is perfectly correct given the question, but probably not what the OP actually intended
I think you mean CONTEXT_(84|5). You're match will match CONTEXT_8, CONTEXT_4, CONTEXT_5 and CONTEXT_|, but not CONTEXT_84. Also, there should be a space or \s* or something before the '='
-1, wrong regex for the problem, as stated by another comment.
3

it depends on your target language, but the main difference between the two is the numbers, so you can do this to get 'CONTEXT_' with at least one number followed by a space and an '=':

CONTEXT_[0-9]+ = 

or this, to get 'CONTEXT_' with min of one, max of two numbers, followed by a space and an '=':

CONTEXT_[0-9]{1,2} = 

3 Comments

While I can understand the last remark, I think you should at least point out that it matches everything - lest it be mistaken for a serious suggestion.
@Draemon, good point, well taken. I have edited the post to remove the flip answer.
Your last example is missing the =
1

CONTEXT_[0-9]+ = *

Comments

1

Your question already contains the answer: you ask

how do I match CONTEXT_84 = or CONTEXT_5 =?

That's already all you need, the only thing missing is how to say or in Regexp, and that's |.

So, your solution is

CONTEXT_84 =|CONTEXT_5 = 

You can shorten that by pulling out the common parts:

CONTEXT_(84|5) = 

And you're done!

Comments

0
CONTEXT_[\d]+ = 

1 Comment

No need for the character class (the []) when matching \d.