【问题标题】:RegEx in C# Replace Method [duplicate]C#替换方法中的正则表达式[重复]
【发布时间】:2019-02-05 00:01:22
【问题描述】:

我正在尝试编写正则表达式来替换下面字符串中的“名称”部分。

 \profile\name\details

其中名称:-可以有特殊字符 - 没有空格

假设我想用 ABCD 替换上面路径中的“名称”,结果将是

 \profile\ABCD\details

Replace 中使用的 RegEx 是什么?
我试过[a-zA-Z0-9@#$%&*+\-_(),+':;?.,!\[\]\s\\/]+$,但它不起作用。

【问题讨论】:

  • 向我们展示您创建的正则表达式。
  • 名称是动态的,只是一个例子。
  • @CinCout 用我使用的示例更新了我的答案。
  • name 是动态的,但字符串的另一部分是常量? \profile\ 和 \details
  • @EIConrado 是的,你是对的,名称是动态的,但其他部分如“\”以及配置文件和详细信息是不变的。

标签: c# regex


【解决方案1】:

由于您的动态部分被两个静态部分包围,您可以使用它们来找到它。

\\profile\\(.*)\\details

现在如果您只想替换中间部分,您可以使用LookAround

string pattern = @"(?<=\\profile\\).*(?=\\details)";
string substitution = @"titi";
string input = @"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;

Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);

或者使用replacement patterns$GroupIndex

string pattern = @"(\\profile\\)(.*)(\\details)";
string substitution = @"$1Replacement$3";
string input = @"\profile\name\details
\profile\name\details
";
RegexOptions options = RegexOptions.Multiline;

Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);

对于可读的nammed group substitution 是可能的。

【讨论】:

  • 我没有解决您在原始问题中的特殊字符集,但您可以在那些正则表达式中简单地使用它。当正则表达式复杂时,我会推荐使用第二个可能更具可读性。如果您需要有关 $ 替换的更多信息,我推荐 MSDN documentation
  • 推荐MSDN:)
  • 我觉得 MSDN 很好。当他们重建文档时,所有的 msdn 链接每 4-5 年就会失效一次。并且文档的 github 非常活跃,使得许多锚死了。 (在这个答案中修复了一个)。但这是一个很好的信息来源。如果我必须选择一个静态信息源,它将是 MSDN 和 referencesource.microsoft.com 其他 StackOverflow。
  • Microsoft TechNet,然后是 MSDN。但现在是 Microsoft Doc (docs.microsoft.com)。我停止关注 2015 年的品牌重塑
猜你喜欢
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
相关资源
最近更新 更多