tags:

views:

150

answers:

6

How do I write a regular expression to match the following

CONTEXT_84 =

or

CONTEXT_5 =

thanks

+6  A: 
CONTEXT_(84|5) =
phatmanace
This is perfectly correct given the question, but probably not what the OP actually intended
Draemon
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 '='
Al
-1, wrong regex for the problem, as stated by another comment.
Adriano Varoli Piazza
+3  A: 

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} =
akf
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
@Draemon, good point, well taken. I have edited the post to remove the flip answer.
akf
Your last example is missing the =
Adriano Varoli Piazza
fixed the second example
Patrick McDonald
thanks, was on my way in to the office.
akf
A: 

CONTEXT_[0-9]+ = *

Mite Mitreski
:) not fast enough
Mite Mitreski
+6  A: 

Hi Matt,

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
crono
+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.
Falaina
Yeah - the explanation is exported from the "Create" Window of RegexBuddy - I found it very helpful when I was learning regex
crono
A: 
CONTEXT_[\d]+ =
mafutrct
No need for the character class (the []) when matching \d.
Daniel
Ah, right, thanks!
mafutrct
+1  A: 

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!

Jörg W Mittag