【问题标题】:regex to replace whole word with specific format C#正则表达式用特定格式 C# 替换整个单词
【发布时间】:2021-08-05 03:10:35
【问题描述】:

我无法从字符串中查找要替换为以前已知格式的字符串。像这样:

  • 输入:"#ITEMJIB_{thisIsNumber}, and test but"

  • 输出:"<div class='module_{thisIsNumber}'></div>, and test but".

感谢您的帮助

【问题讨论】:

  • “我遇到了麻烦” -- 具体是什么?你尝试了什么?那做了什么?这和你想要的有什么不同?您具体在哪些方面需要帮助?尽管有一些人的做法,Stack Overflow 并不是一个代码编写服务。

标签: c# regex


【解决方案1】:

您可以匹配 #ITEMJIB_(\{\d+\}) 并替换为 <div class='module_$1'></div> - 该号码将被捕获到组 1 并在替换时使用。

如果花括号不是字符串的一部分 (#ITEMJIB_1),请从模式中删除 \{\}

工作示例:https://regex101.com/r/MxKZn5/1

C# 示例:

var input = "item #ITEMJIB_{1}, and test but #ITEMJIB_{2}";
var output = Regex.Replace(input, @"#ITEMJIB_(\{\d+\})", "<div class='module_$1'></div>");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    相关资源
    最近更新 更多