开发者

Using regular expression to extract full words from text

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)");


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]+)

Another way of writing this that accounts for multiple spaces between words is:

(\w+)\s+(\w+\s+\w+)


/(Scottish) (Premier League)/


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.


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*) (.*) \(/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜