[英]How can I replace more than one string with another using just one Regex or do I have to use multiple Regex and temp strings?
I have a variable being given a value like this: 我有一个变量被赋予这样的值:
vm.WordType = phrase.WordType;
where the value of phrase.WordType can be something like this: 其中statement.WordType的值可以是这样的:
"Godan verb with ru ending, Transitive Verb"
and I would like to change it to 我想将其更改为
"Godan v with ru end, Transitive v"
I can use Regex to for example replace verb with v but is there a way that I can use Regex to do more replacements, such as replace "ending" with "end" or do I have to somehow string together multiple Regex and use temp variables? 我可以使用Regex例如用v替换动词,但是有一种方法可以使用Regex进行更多替换,例如用“ end”替换“ end”或我必须以某种方式将多个Regex串在一起并使用临时变量?
vm.WordType = Regex.Replace(phrase.WordType, "verb", "v", RegexOptions.IgnoreCase);
You could of course just call Regex.Replace
2 times - the first time replacing "verb", the second time replacing "ending". 您当然可以只调用Regex.Replace
2次-第一次替换“动词”,第二次替换“结束”。
If you don't like that, you could do it in one single regex like this: 如果您不喜欢这样,可以在一个正则表达式中执行以下操作:
Regex.Replace("Godan verb with ru ending, Transitive Verb", "(v)erb|(end)ing", "$1$2", RegexOptions.IgnoreCase)
The regex I used here is: 我在这里使用的正则表达式是:
(v)erb|(end)ing
It matches either "verb" and puts "v" into group 1, or it matches "ending" and puts "end" into group 2. 它匹配“动词”并将“ v”放入组1,或者匹配“ end”并将“ end”放入组2。
The replacement is $1$2
, which means group 1 and group 2. 替换为$1$2
,表示组1和组2。
Let's say you also want to replace "transitive" with "trans", you could easily change the regex to: 假设您还想用“ trans”替换“ transitive”,则可以轻松地将正则表达式更改为:
(v)erb|(end)ing|(trans)itive
and the replacement to all three groups: 并替换为所有三个组:
$1$2$3
Note that this approach will preserve case, so "Verb" becomes "V" and "verb" becomes "v". 请注意,此方法将保留大小写,因此“动词”变为“ V”,“动词”变为“ v”。 If this is undesirable, you can pass in a MatchEvaluator
to convert them to lowercase: 如果不希望这样做,则可以传入MatchEvaluator
将其转换为小写形式:
Regex.Replace(
"Godan verb with ru ending, Transitive Verb",
"(v)erb|(end)ing",
x => string.Join("", x.Groups.Cast<Group>().Skip(1).Select(y => y.Value)).ToLowerInvariant(),
RegexOptions.IgnoreCase)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.