2009-10-12 143 views
25

我正在查找將返回字符串中第一組括號內容的正則表達式模式。從括號內返回文本的正則表達式模式

例如,

text text text text (hello) text (hello2) (hello3) text 

將返回"hello"

有誰知道什麼圖案看起來像C#?

+1

標題變更請求。不應該使用'括號'這個詞來表示'['而不是'('(括號))嗎? - crokusek – crokusek 2014-03-13 18:13:42

回答

59

正規表達式會是這個樣子:

\(([^)]*)\) 

模式屍檢:

\( - 文字 「(

( - 子模式的開始:

[^)]*比賽0個或多個不是「)」的字符 - 注意:我們正在定義一個角色組,所以我們不必在這裏逃脫)角色。

) - 子模式的結束

\) - 文字「)

完整的模式將匹配括號,並在他們裏面的文字,第一子模式將只匹配括號內的文字(見C#參考如何讓他們 - 我不說話C#;))

+1

這是否適用於不返回括號?只有內容? – Grant 2009-10-12 07:50:51

+2

這看起來是正確的。一個實際的'('字符,然後開始一個組,然後匹配零個或多個非')'字符,然後關閉該組;然後匹配一個實際的')'字符。由此產生的小組應該得到什麼是在parens裏面。這個例子有點混亂,因爲開始一個組的角色恰好是'(',我們正在尋找匹配一個實際的'(')。要關閉'('角色的「魔術」並且只匹配一個實際的' ('字符,我們先放一個反斜槓,就像「\\(」,如圖所示 – steveha 2009-10-12 07:52:13

+0

這不會自動返回括號 – 2009-10-12 07:53:29

2

裸正則表達式:

\((.*?)\) 

在Python中,你可以使用這種方式:

import re 

rx = re.compile(r'\((.*?)\)') 
s = 'text text text text (hello) text (hello2) (hello3) text' 
rxx = rx.search(s) 
if rxx: 
    print(rxx.group(1)) 
+0

Python的正則表達式不會在這裏進行貪婪匹配嗎?返回'(你好)文本(hello2)(hello3)'作爲第一個也是唯一的匹配? – 2009-10-12 07:58:02

+0

好的,表達「。*?」是Python中「。*」的非貪婪版本。它也可以在C#中工作嗎? – steveha 2009-10-12 07:59:53

+0

嗯,非貪婪的伎倆可能在C#中工作,請參閱此頁面中的「懶惰和貪婪匹配」:http://www.dijksterhuis.org/regular-expressions-in-csharp-the-basics/ – steveha 2009-10-12 08:01:29

1

如果字符串都比較小,你可以使用一個取代代替比賽

string s = Regex.Replace("text text text text (hello) text (hello2) (hello3) text", @"^.*?\(([^)]*)\).*$", "$1"); 
5

這將返回僅在第一組括號內:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Match match = Regex.Match("foo bar (first) foo bar (second) foo", @"\((.*?)\)"); 

      if (match.Groups.Count > 1) 
      { 
       string value = match.Groups[1].Value; 
       System.Console.WriteLine(value); 
      } 
     } 
    } 
}