【发布时间】:2014-09-11 11:34:59
【问题描述】:
我想有一种方法从字符串中捕捉年份并将主题放在( 和) 之间,而且我对正则表达式非常陌生。例如
This is 2014 and the next year will be 2015
将会是
This is (2014) and the next year will be (2015)
我正在使用\d{4} 来捕获年份,但我不知道是否可以将字符串发送到下一个参数?
【问题讨论】:
我想有一种方法从字符串中捕捉年份并将主题放在( 和) 之间,而且我对正则表达式非常陌生。例如
This is 2014 and the next year will be 2015
将会是
This is (2014) and the next year will be (2015)
我正在使用\d{4} 来捕获年份,但我不知道是否可以将字符串发送到下一个参数?
【问题讨论】:
下面的正则表达式将准确捕获输入字符串中的四位数字。在替换部分中,在捕获的数字之前和之后添加括号。
正则表达式:
(\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);
模式解释:
() - Capturing groups.
\b - 称为单词边界。它匹配单词字符\w 和非单词字符\W。\d{4}- 正好匹配四位数字。\b - 单词字符和非单词字符之间的匹配。string pattern = @"\(\d{4}\)";
string result = Regex.Replace(str, pattern , "($1)");
这将找到括在开/关括号中的任何 4 位数字。 如果年份数字可以改变,我认为 Regex 是最好的方法。
相反,这段代码会告诉你是否有匹配的模式
【讨论】:
在 C# 中,你会这样做:
Input: "This is 2014 and the next year will be 2015"
Pattern: "\d{4}"
Replacement: "($0)"
但这将匹配所有 4 位数长的数值,根据您的模式。
注意
$0 或 $& 在字符串替换模式中用于引用整个匹配项而不是任何捕获的子字符串。
【讨论】:
$1 而不是$0,这很有效。有什么区别?
试试这个
"This is 2014 and the next year will be 2015".replace(/(\d{4})/gi, '($1)');
【讨论】:
System.String.Replace() 是否使用正则表达式?