什麼是正則表達式來獲取雙引號內的文本。正則表達式在雙引號中獲取文本
我正則表達式是:
"\"([^\"]*)\""
例如:"I need this"
輸出:I need this
我越來越:"I need this"
什麼是正則表達式來獲取雙引號內的文本。正則表達式在雙引號中獲取文本
我正則表達式是:
"\"([^\"]*)\""
例如:"I need this"
輸出:I need this
我越來越:"I need this"
用下面的正則表達式,你會得到你想要的東西,沒有任何分組
(?<=")[^"]+?(?=")
代碼來獲取引用的文字:
string txt = "hi my name is \"foo\"";
string quotedTxt = Regex.Match(txt, @"(?<="")[^""]+?(?="")").Value;
這裏是你的問題的完整解決方案:
string sample = "this is \"what I need\"";
Regex reg = new Regex(@"""(.+)""");
Match mat = reg.Match(sample);
string foundValue = "";
if(mat.Groups.Count > 1){
foundValue = mat.Groups[1].Value;
}
Console.WriteLine(foundValue);
個
打印:
我需要什麼
這是正確的答案,但你能解釋它爲什麼有效嗎?(他們只想打印組,而不是整個匹配)? – 2013-05-10 16:34:01
最初的正則表達式工作得很好,而不必訴諸於'。*'(或在這種情況下'。+')。但是+1指出需要的是'Groups [1]'而不是'Groups [0]'。我懷疑這是OP項目的問題。 – 2013-05-10 16:38:21
Too遲到發佈答案?
string text = "some text \"I need this\" \"and also this\" but not this";
List<string> matches = Regex.Matches(text, @"""(.+?)""").Cast<Match>()
.Select(m => m.Groups[1].Value)
.ToList();
它有幫助,但是,我也得到了引號後的文字「」......也許你可以改變它......感謝例子:「它是一切都好」這也是即將....輸出:-it這一切都是好的,這也來..感謝 – 2013-05-10 16:49:58
@bhargava這是奇數,我沒有得到這個 – 2013-05-10 17:39:28
問題是,前瞻並不消耗結束報價。正則表達式開始在第一場比賽結束的地點尋找第二場比賽,並且幾乎立即找到第二場比賽,因爲後場比賽與先前匹配的報價相匹配。 – 2013-05-10 20:37:51