问题描述
我需要使用 RegEx.Replace 仅替换输入字符串中的某些命名组.
所以我可能有这样的模式:
"^(?.+)(?(\d{2})|CM|RM|PM|CN|RN){1}(?(\d{2})|CM|RM|PM|CN|RN){1}((#(?[#,\.\+\-%0]+))*)$"
诸如 CM、RM 之类的令牌正在使用带有 MatchEvaluator 的 Regex.Replace 替换.但是,这应该只替换 FirstPeriod 和 LastPeriod 组中的字符.
示例输入:"FIELDCNS 01CM"
所需的输出:"FIELDCNS 0104"
错误的输出:"FIELD**04**S 0104"
这是可能的,还是我最好只是拔出我想更换的零件然后重新组装?
我不完全确定我明白你在问什么,但如果你只想在你与常规匹配的部分之间替换一些字符串表达式那么诀窍是捕获所有您不想替换的位.例如,要将所有 "blah"
替换为 "XXXXX"
,但仅在 "foo" 和 "bar"
之间,你可以这样做:
Dim regex As Regex = new Regex("(foo.*)blah(.*bar)")Console.WriteLine(regex.Replace(_"blah foo bar baz blah baz bar blah blah foo blah", "$1XXXXXX$2"))Console.ReadLine()
blah foo bar baz XXXXX baz bar blah blah foo blah
I need to use RegEx.Replace to replace only certain named groups in my input string.
So I might have a pattern like:
"^(?<NoReplace>.+)(?<FirstPeriod>(\d{2})|CM|RM|PM|CN|RN){1}(?<LastPeriod>(\d{2})|CM|RM|PM|CN|RN){1}((#(?<NumberFormat>[#,\.\+\-%0]+))*)$"
Tokens such as CM, RM are being replaced using Regex.Replace with a MatchEvaluator. However, this should only be replacing characters in the FirstPeriod and LastPeriod groups.
Example input:"FIELDCNS 01CM"
Desired output:"FIELDCNS 0104"
Incorrect output:"FIELD**04**S 0104"
Is this possible or am I best just pulling out the parts I want to replace and re-assembling afterwards?
I'm not entirely sure I understand what you're asking, but if you're wanting to replace some strings only between parts you're matching with regular expressions then the trick is to capture all the bits you don't want to replace. For example, to replace all "blah"
s with "XXXXX"
s but only in between a "foo" and a "bar"
, you could do:
Dim regex As Regex = new Regex("(foo.*)blah(.*bar)")
Console.WriteLine(regex.Replace( _
"blah foo bar baz blah baz bar blah blah foo blah", "$1XXXXX$2"))
Console.ReadLine()
这篇关于如何正则表达式替换命名组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!