[英]How can I replace string with regular expressions?
I replace my string as below; 我将字符串替换如下:
string str = "Opps V 14";
str = str.Replace("V 14", "V14");
But numeric part of string is not static. 但是字符串的数字部分不是静态的。 Sometimes it can be "V 17", "V 13" etc.. 有时可以是“ V 17”,“ V 13”等。
How can I replace that with regular expressions globally? 如何在全球范围内将其替换为正则表达式?
This will replace the space between V and a digit with nothing: 这将用任何内容替换V和一个数字之间的空格:
string pattern = @"(?<=\bV) (?=\d)";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, "");
(?<=\\bV)
is a lookbehind assertion and means "preceded by V", \\b
is a word boundary. (?<=\\bV)
是一个后置断言,表示“以V开头”, \\b
是单词边界。
(?=\\d)
is a lookahead assertion and means "followed by a digit" (?=\\d)
是前瞻性断言,表示“后跟数字”
Lookaround assertions are not part of the match result but only checks. 环视断言不是匹配结果的一部分,而只是检查。 This is the reason why only the space is removed. 这就是为什么只删除空间的原因。
note: you must include using System.Text.RegularExpressions;
注意:您必须包括using System.Text.RegularExpressions;
at the begining of the file. 在文件的开头。
Assuming that except the number, rest of the string is static, then its as simple as removing the space after V: 假设除数字外,字符串的其余部分都是静态的,则其与删除V后的空格一样简单:
str = str.Replace("V ","V"); str = str.Replace(“ V”,“ V”);
class Program
{
static void Main(string[] args)
{
string str = "Opps V 14";
string[] temp = str.Split(' ');
str = String.Join(" ", temp.Take(2)) + temp.Last();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.