2014-09-11 48 views
0

我想有一個方法來捕捉字符串中的年份,並將主題放在()之間,我很樂意在正則表達式中使用。例如如何在Regex.Replace()中獲得匹配?

This is 2014 and the next year will be 2015 

將是

This is (2014) and the next year will be (2015) 

我使用\d{4}捕獲的一年,但我不知道是否有可能將字符串發送到下一個參數?

回答

3

下面的正則表達式會捕獲輸入字符串中的四位數字。在替換部分中,在捕獲的數字之前和之後添加括號。

正則表達式:

(\b\d{4}\b) 

替換字符串:

($1) 

代碼:

string str = "This is 2014 and the next year will be 2015"; 
string result = Regex.Replace(str, @"(\b\d{4}\b)", "($1)"); 
Console.WriteLine(result); 

IDEONE

模式Explanti於:

  • () - Capturing groups.
  • \b - 這就是所謂的單詞邊界。它匹配單詞字符\w和非單詞字符\W
  • \d{4} - 匹配正好四位數。
  • \b - 單詞字符和非單詞字符之間的匹配。
+0

另一個[DEMO](https://dotnetfiddle.net/k3ckny),你這麼快男.. – 2014-09-11 11:45:23

+1

@YuliamChandra這是更好地使用字邊界。 – 2014-09-11 11:46:54

+0

謝謝:)那工作:) [這](http://ideone.com/fnA7LJ)是真正的測試 – 2014-09-11 11:47:32

0

試試這個

"This is 2014 and the next year will be 2015".replace(/(\d{4})/gi, '($1)'); 
+0

不與C#你不會! – ne1410s 2014-09-11 11:41:14

+0

'System.String.Replace()'使用正則表達式嗎? – 2014-09-11 11:45:25

1

在C#中,你可以這樣做:

Input: "This is 2014 and the next year will be 2015" 
Pattern: "(\d{4})" 
Replacement: "($0)" 

但是,這將匹配的是4位長,按你的模式的所有的數值。

+0

我使用'$ 1'而不是'$ 0'並且工作正常。有什麼區別? – 2014-09-11 11:44:47

+0

因爲捕獲組。您需要引用組索引1 inorder以獲取第1組中的值。 – 2014-09-11 11:47:38

+0

也許可以把它看作捕獲匹配的索引(用正則表達式模式中的圓括號表示)。你可以查看這個資源 - 我總是使用它:http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.90).aspx – DvS 2014-09-11 11:55:13

1
string pattern = @"\(\d{4}\)"; 
string result = Regex.Replace(str, pattern , "($1)"); 

這將查找打開/關閉括號內的任何4位數字。 如果年份數字可以改變,我認爲正則表達式是最好的方法。

代替此代碼會告訴你,如果有一個匹配你的格局

+0

你不明白這個問題。我使用正則表達式,但我不知道如何檢索匹配的字符串。 – 2014-09-11 15:40:28

+0

對不起,我編輯了我的答案 – 2014-09-11 15:59:24

相關問題