【问题标题】:Regex replace and divide正则表达式替换和划分
【发布时间】:2015-12-23 19:39:03
【问题描述】:

我只需要从字符串中提取数字,到目前为止我还没有遇到任何问题。

我使用了这个代码:

string test = "N.11 Test 11";
string example = Regex.Replace(test, @"[^\d]", "");

输出:“1111”。

那么..如何用符号分隔两个值?

例如:“11:11”。

(抱歉英语不好)

【问题讨论】:

  • 只需匹配所有数字序列并将结果数组与: 连接。

标签: c# regex string replace


【解决方案1】:

不使用替换的简单方法是这样的。

string test = "N.11 Test 11";
var result = string.Join(":", Regex.Matches(test, @"\d+").OfType<Match>());

请注意,最好使用 Regex 变量而不是使用像 Regex.Matches 这样的静态方法。如果您想一遍又一遍地使用相同的模式,那么每次创建新的正则表达式并不优雅。所以这样更好。

public static Regex digits = new Regex(@"\d+");
//...
var result = string.Join(":", digits.Matches(test).OfType<Match>());

【讨论】:

  • 完美。非常感谢
【解决方案2】:

使用这个正则表达式:[^\d]*(\d+).*?(\d+) 对两个数字进行分组,然后替换为 \1:\2

【讨论】:

    【解决方案3】:
    Try this:    
    
    String test = "N.11 Test 11";
    
    String example = test.replaceFirst( "\\s", ":" );
    example = example.replaceAll( "[^:\\d]", "" );
    System.out.println("The answer is " + example);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多