我有一个这样的字符串:“编程是我的热情,我喜欢程序”
现在我需要使用 Regex Replace 来更改它。每个包含表达式“程序”的单词都应切换为:
<a href="http://codeguru.pl" title="programming">programming</a>
任何帮助将不胜感激。
String.Replace是最好的选择。
var input = "programming is my passion, I love programs";
var replacefrom = "program";
var tobereplaced =@"<a href=""http://codeguru.pl"" title=""programming"">programming</a> is my passion";
var output = input.Replace(replacefrom, tobereplaced)
Regex regex = new Regex("program");
var outputRegex = regex.Replace(input, tobereplaced); // input, tobereplaced from above snipped
输出
<a href="http://codeguru.pl" title="programming">programming</a> is my passionming is my passion, I love <a href="http://codeguru.pl" title="programming">programming</a> is my passions
一条线就足够了:
new Regex(@"\b\w*program\w*\b").Replace("programming is my passion, I love programs", @"<a href=""http://codeguru.pl"" title=""programming"">programming</a>");
where\b\w*program\w*\b
匹配任何包含program
.
如果要根据匹配的单词更改链接的文本,请使用反向引用:
new Regex(@"(\b\w*program\w*\b)").Replace("programming is my passion, I love programs", @"<a href=""http://codeguru.pl"" title=""programming"">$1</a>");
此版本在模式周围添加括号,并使用$1
(而不是硬编码字符串“ programming
”)来引用匹配的单词。现在输出将是:
<a href="http://codeguru.pl" title="programming">programming</a> is my passion, I love <a href="http://codeguru.pl" title="programming">programs</a>
解决方案..
Pattern pattern = Pattern.compile("(\\w+|\\W)");
Matcher m = pattern.matcher("programming is my passion, I love programs");
while (m.find())
{
Pattern pattern1 = Pattern.compile("(program)");
Matcher m1 = pattern1.matcher(m.group());
if(m1.find())
System.out.print(m.group().replace(m.group(), "<a href="+"http://codeguru.pl"+" title="+"programming"+">programming</a>"));
else
System.out.print(m.group());
}
输出:
<a href=http://codeguru.pl title=programming>programming</a> is my passion, I love <a href=http://codeguru.pl title=programming>programming</a>