【发布时间】:2011-07-05 17:03:16
【问题描述】:
在以下示例中,我需要将所有出现的\b 替换为<b>,并将所有出现的\b0 替换为</b>:
敏捷的\b 棕狐\b0 跳过\b 懒惰的狗\b0。。谢谢
【问题讨论】:
-
问题是什么?您在寻找正则表达式生成器吗?
-
史蒂夫,我遇到了一个问题,正在尝试不同的方法来解决它。到目前为止没有运气。
在以下示例中,我需要将所有出现的\b 替换为<b>,并将所有出现的\b0 替换为</b>:
敏捷的\b 棕狐\b0 跳过\b 懒惰的狗\b0。。谢谢
【问题讨论】:
正则表达式对此非常过分(而且经常如此)。一个简单的:
string replace = text.Replace(@"\b0", "</b>")
.Replace(@"\b", "<b>");
足够了。
【讨论】:
你不需要正则表达式,你可以简单地replace the values with String.Replace.
但如果你想知道这怎么可能是done with regex (Regex.Replace),这里有一个例子:
var pattern = @"\\b0?"; // matches \b or \b0
var result = Regex.Replace(@"The quick \b brown fox\b0 jumps over the \b lazy dog\b0.", pattern,
(m) =>
{
// If it is \b replace with <b>
// else replace with </b>
return m.Value == @"\b" ? "<b>" : "</b>";
});
【讨论】:
var res = Regex.Replace(input, @"(\\b0)|(\\b)",
m => m.Groups[1].Success ? "</b>" : "<b>");
【讨论】:
作为一个快速而肮脏的解决方案,我会分两次运行:首先将“\b0”替换为"</b>",然后将“\b”替换为"<b>"。
using System;
using System.Text.RegularExpressions;
public class FadelMS
{
public static void Main()
{
string input = "The quick \b brown fox\b0 jumps over the \b lazy dog\b0.";
string pattern = "\\b0";
string replacement = "</b>";
Regex rgx = new Regex(pattern);
string temp = rgx.Replace(input, replacement);
pattern = "\\b";
replacement = "<b>";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(temp, replacement);
}
}
【讨论】: