【问题标题】:Regex to add space between capital letter, in addition to replacing the word 'And' with &正则表达式在大写字母之间添加空格,除了用 & 替换单词 'And'
【发布时间】:2014-03-19 01:19:01
【问题描述】:

现在我可以用'&' 替换'And',但我还需要在大写字母之间添加一个空格。

例如:

字符串:类别名称到类别名称

和 CategoryAndName 到类别和名称

当前正则表达式:

System.Text.RegularExpressions.Regex.Replace( stringText, "(.+)And", "$1 & " )

【问题讨论】:

  • This And 会变成This <extra space>And 会怎样?另外,不要在你的正则表达式中使用(.+),使用后向。 (.+) 将匹配字符串中的所有文本(包括 And's)直到最后一个 And。
  • This And 应该变成 This &

标签: c# asp.net regex


【解决方案1】:

这些是您可能需要的两个正则表达式。

使用lookbehind 检查大写字母是否紧跟在小写字母之后。

stringText = Regex.Replace( stringText, "(?<=[a-z])([A-Z])", " $1" );
// You can also use `(?<=[a-z])(?=[A-Z])` and replace with single space also.

对于这个,它使用lookbehindlookahead 检查And 是否在任何字母之间。

stringText = Regex.Replace( stringText, "(?<=[a-zA-Z])And(?=[a-zA-Z])", " & " );

【讨论】:

  • 是否可以将它们都放在一个 regex.replace 中
  • @xphong 以我有限的知识我不知道。
  • 你有两个不同的替换字符串,所以不,你必须替换所有一个,然后再替换另一个。
猜你喜欢
  • 1970-01-01
  • 2013-11-17
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多