如何编写正则表达式从括号中提取单个单词?

时间:2011-04-01 22:37:33

标签: c# regex

我有一个包含文字的长字符串。我想提取括号(' ')之间的每个单词,但只要在括号之间只有一个单词(IE,没有空格)。

例如,在下面:

<ul>
<li>7-SPEED DOUBLE CLUTCH AUTOMATIC TRANSMISSION (2TC)</li>
<li>MOONLIGHT BLACK SOFT TOP (3YA)</li>
<li>8-WAY PWR FRONT BUCKET SEATS -inc: driver memory, 2-way adjustable headrests, exterior mirror memory (459)</li>
<li>BLACK SAPPHIRE METALLIC (475)</li>
<li>HEATED FRONT SEATS (494)</li>
<li>GLACIER SILVER ALUMINUM TRIM (REQ: ZMP M Sport Pkg) (4MG)</li>
<li>NAVIGATION SYSTEM -inc: hard drive, HD Radio, real-time traffic info, voice command, cupholders (609)</li>
<li> ASSIST W/BLUETOOTH -inc: (4) year subscription (w/609 Navigation System-inc: Online info services) (639)</li>
<li>IPOD & USB ADAPTER (6FL)</li>
<li>M SPORT STEERING WHEEL-MOUNTED SHIFT PADDLES (REQ: ZSP Sport Pkg or ZMP M Sport Pkg & 205 Auto Trans) (7XA)</li>
<li>BLACK, BOSTON LEATHER SEAT TRIM (LWSW)</li>
<li>M SPORT PKG -inc: 18&quot; x 7.5&quot; front & 18&quot; x 8.5&quot; rear double-spoke light alloy wheels (style 261M), P215/40R18 front & 245/35R18 rear performance tires, 8-way manual front sport seats, M sport steering wheel, shadowline exterior trim, increased top speed limiter (w/205 Auto Trans REQ: 7XA Shift Paddles) (ZMP)</li>
<li>PREMIUM PKG -inc: Boston leather seat trim, universal garage door opener, auto-dimming pwr folding exterior mirrors w/memory, auto-dimming rearview mirror w/digital compass, pwr front seats w/pwr lumbar support,  Assist w/(4) year subscription, Bluetooth, illuminated exterior door handles, front/rear reading lights, front footwell illumination, driver/front passenger illuminated vanity mirrors, ambiance interior lighting (ZPP)</li>
<li>VALUE PKG -inc: Boston leather seat trim, iPod and USB adapter (ZVP)</li>
</ul>

我想得到结果

2TC 3YA 459 475 494 4MG 609 639 6FL 7XA LWSW ZMP ZPP ZVP

解析此问题的最佳方法是什么?如果重要的话,我在C#中实现它

1 个答案:

答案 0 :(得分:1)

正则表达式\((\S+)\)应该可以解决问题。

string pattern = @"\((\S+)\)";
MatchCollection matches = Regex.Matches(str, pattern);