簡體   English   中英

使用正則表達式從文本中提取完整單詞

[英]Using regular expression to extract full words from text

我一直在分析數據,我得到了一個像這樣的字符串:

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

我想使用正則表達式提取Scottish匹配組1和Premier League第2組的“蘇格蘭超級聯賽”。

請告訴我使用正則表達式的方法。

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

如果您只想匹配每個特定的單詞,則您的正則表達式可能類似於:

(Scottish) (Premier League)

如果要匹配第一個單詞,則接下來的兩個單詞:

([\w]+) ([\w]+ [\w]+)

另一種寫出單詞之間多個空格的方式是:

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

/(蘇格蘭)(英超聯賽)/

基本和直接:

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

您可能想要更通用的匹配:

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

這些是Perl; 下次再具體一點。

此外,請使用RegexBuddyExpresso之類的工具來幫助自己。

鑒於您只給出了要應用正則表達式的一個字符串,因此很難確定該解決方案是否適用於您的其他各種情況:

/^(\w*) (.*) \(/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM