tags:

views:

119

answers:

4

I have been working with parsing data, I got a string like:

"Scottish Premier League (click here to open|close this coupon)"

I would like to extract "Scottish Premier League" with Scottish Matching Group 1 and Premier League Matching Group 2, using regular expression.

Please show me the way to do that using regular expression.

MatchCollection matchCol = reg.Matches("Scottish Premier League (click here to open|close this coupon)");
A: 

/(Scottish) (Premier League)/

echo
I have to fix location is Scottish and then I can get division Premier League after replace Scottish => empty.Thanks for all
QuachNguyen
+1  A: 

Given that you only gave one string to which the regex would be applied, it is hard to tell if this solution would work for your various other cases:

/^(\w*) (.*) \(/
ZombieDev
+2  A: 

If you just want to match each specific word then your regex could be something like:

(Scottish) (Premier League)

If you want to match the first word then the next two:

([\w]+) ([\w]+ [\w]+)
VoDurden
This solution i would recommend. Works perfectly.
Arto Uusikangas
This is better written as `/^(\w+) (\w+ \w+)/` because there's no need to put the square brackets around a single character and you only want the starting part of the string not, for example, "here", "to open"
dlamblin
@dlamblin - good point. I'd also change spaces to `\s+` .
Kobi
A: 

Basic and direct:

$s =  "Scottish Premier League (click ... coupon)";
$s =~ m/(Scottish) (Premier League)/;
print "Match groups one and two: '$1' '$2'\n";

You probably wanted more generalized matching:

$s =  "Generalized Matching on a string (click ... coupon)";
$s =~ m/^(\S+)\s(.+)\s+\(click/;
print "Match groups one and two: '$1' '$2'\n";

These are Perl; be more specific next time.

Also, help yourself, use a tool, like RegexBuddy or Expresso.

dlamblin
I set -1 before you edited (within the 5min margin), and now it won't let me change, sorry. Though why do you include the first (apparently completely jocular) example?
Roger Pate
@R. Pate. Totally not a problem; you'll learn to wait to down vote when an answer is a day old or more. To answer your question: Because it is correct. I do not play guessing games to answer questions.
dlamblin