简体   繁体   English

如何用正则表达式替换字符串?

[英]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.

相关问题 我可以在 C# 中将正则表达式与 String.Replace 一起使用吗? - Can I use regular expressions with String.Replace in C#? 如何使用正则表达式替换C#中的一部分字符串? - How to use Regular expressions to replace a part of string in C#? 我如何用正则表达式检查字符串,该字符串包含12个字符并包含0-9a-f? - How I can check a string with Regular expressions about the string has 12 characters and contains 0-9a-f? 使用正则表达式匹配和替换文本中的字符串 - Match and replace string in text using regular expressions 正则表达式替换包含字符@的字符串 - Regular expressions replace string containing character @ 如何使用正则表达式从输入字符串中提取所有非字母数字字符? - How can I extract all non-alphanumeric characters from an input string using Regular Expressions? 如何使用正则表达式在定义的单词之间捕获任意字符串? - How can I catch an arbitrary string between defined words using regular expressions? 正则表达式(.NET)-如何匹配在字符串末尾包含可变位数的模式? - Regular Expressions (.NET) - How can I match a pattern that contains a variable number of digits at the end of the string? 如何使用 C# 中的正则表达式查找和替换较大文件 (150MB-250MB) 中的文本? - How can I find and replace text in a larger file (150MB-250MB) with regular expressions in C#? 如何使用C#和正则表达式解析字符串? - How do I parse a string using C# and regular expressions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM