简体   繁体   English

C#正则表达式替换问号

[英]C# Regular expression replace question mark

I want to replace question mark character ? 我要替换问号字符? with text Rs if ? 与文本Rs如果? is followed by numbers. 后跟数字。

This is what I have tried. 这就是我尝试过的。 But not working. 但是没有用。

 string str = "DFg sdfsdaf ?145 dfgsdf ?fg";
 str = str.Replace(@"\\?", "Rs");
 Console.WriteLine(str);

Desired output: 所需的输出:

DFg sdfsdaf Rs145 dfgsdf ?fg

Please help. 请帮忙。

Try this: 尝试这个:

Regex.Replace(str, @"\?(\d)", @"Rs$1")

It will match a literal question mark followed by a digit and replace it with Rs followed by that digit. 它会与文字问号和一个数字相匹配,并用Rs和该数字代替。 Question marks followed by non-digits are left unchanged. 带数字的问号保持不变。

Example: 例:

var str = "DFg sdfsdaf ?145 dfgsdf ?fg";
Console.Out.WriteLine(Regex.Replace(str, @"\?(\d)", @"Rs$1"));

Output: 输出:

DFg sdfsdaf Rs145 dfgsdf ?fg

Try like this too: 也尝试这样:

System.Text.RegularExpressions.Regex.Replace(str,@"\?(?=\d+)","Rs");

I would recommend this read. 我会推荐这个读。 The above pattern looks for ? 上面的图案找? and checks if it is followed by digit one or more time then replaces ? 并检查是否后面跟着一个或多个digit然后替换? with Rs . Rs

Try this Regex 试试这个正则表达式

\\?((?:\d+))

Use Regex to handle this:- 使用正则表达式来处理此问题:

  Regex oRegex = new Regex(@"\?((?:\d+))");
  str = oRegex.Replace(str, "Rs$1");

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

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