简体   繁体   English

C#,使用正则表达式查找并替换单词中的某些字符?

[英]C#, using a regular expression to find and replace certain characters in a word?

I need something that will find a word enclosed in two "%" signs, and replace the first % with a [ and the second % sign with a ] . 我需要的东西,会发现封在两个“%”的招牌字,并更换第一%[和第二%带符号]

So in the string "This is dummy text %with% percent signs" It will then make it "This is dummy text [with] percent signs" 因此,在字符串“这是带有%百分号的虚拟文本”中,它将变成“这是[带有]百分号的虚拟文本”

EDIT: Would there be a way to search and replace two different things in the same regex? 编辑:是否有一种方法可以在同一正则表达式中搜索和替换两个不同的东西? Like I need to replace %blah% with [blah] but also %~dp1 with [~dp1] the %~dp1 call is in the format %~(could be some letters here)(always ends with a single digit thats how you know the call is over) sorry this is the last thing :) 就像我需要用[blah]替换%blah%,也要用[〜dp1]替换%〜dp1一样,%〜dp1调用的格式为%〜(此处可能是一些字母)(总是以一位数字结尾,这就是您的方式知道电话已经结束)抱歉,这是最后一件事:)

I would match the whole substring enclosed by the special characters, and replace it with a string containing the same inner characters but with brackets instead of percent signs. 我将匹配用特殊字符括起来的整个子字符串,并将其替换为包含相同内部字符但带有方括号而不是百分号的字符串。 Make sure you use nongreedy matching if the input can have many of these substrings: 如果输入中可以包含许多这些子字符串,请确保使用非贪婪匹配:

Regex.Replace("This is dummy text %with% percent signs", "%(.*?)%", @"[$1]");

尝试这个:

Regex.Replace(s, "%([^%]+)%", "[$1]")

Use a MatchEvaluator to provide the replacement value. 使用MatchEvaluator提供替换值。 Alternate with (i++ % 2) 替换为(i++ % 2)

int i = 0;
Regex.Replace(s, "%", m => (i++ % 2) == 0 ? "[" : "]");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM