从Readline with Regex中删除数字序列

时间:2015-07-19 16:44:37

标签: c# regex

我有以下示例字符串:

   string s = Console.ReadLine();
   s= {6} {7613023456148 } {7.040 } {56780} {Sample String}

如何使用正则表达式或类似方法实现以下目标:

  • 删除以7开头并且长度为13位的行中的所有数字。
  • 删除所有十进制数字。

输出

s = {6} {56780} {Sample String}

2 个答案:

答案 0 :(得分:0)

您可以使用空字符串替换捕获的字符串后使用正则表达式:

7\d{12}|\d\.\d+

但请注意,如果您的号码在{}范围内,则需要:

\b{\s*7\d{12}\s*}\b|\b{\s*\d+\.\d+\s*}\b

请参阅演示https://regex101.com/r/dL1vF4/1

答案 1 :(得分:0)

您正在寻找此正则表达式:

var s = "{6} {7613023456148 } {7.040 } {56780} {Sample String}";
s = Regex.Replace(s, @"\s*{(?:\s*7[0-9]{12}\s*|\d+\.\d+\s*)}", string.Empty);
Console.WriteLine(s); // ==> "{6} {56780} {Sample String}"

请参阅IDEONE demo

REGEX 匹配{...}内的可选空格(\s*)前面的2个备选项:

  • \s*7[0-9]{12}\s* - optional whitespace followed with 7`,然后是12位数字和可选空格
  • \d+\.\d+\s* - 一个或多个数字,一个.小数点分隔符,再一个或多个数字,以及可选的空格。

由于您的所有值都在{...}内,因此您不需要单词边界。