只得到整数,不包括整个十进制



我有一个示例字符串'((1/1000)*2375.50)'

我想要得到1和1000这是一个INT

我尝试了这个REGEX表达式:

  • -?d+(.d+)? =>匹配1, 1000, and 2375.50
  • -?d+(?!(.|d+)) =>匹配1, 1000, and 50
  • -?d+(?!.d+&(?![.]+[0-9]))? => 1, 1000, 2375, and 50

我必须使用什么表达式来匹配(1 and 1000)?

所以基本上你需要匹配前面或后面没有小数点或其他数字的数字序列?为什么不试试呢?

[TestCase("'((1/1000)*2375.50)'", new string[] { "1", "1000" })]
[TestCase("1", new string[] { "1" })]
[TestCase("1 2", new string[] { "1", "2" })]
[TestCase("123 345", new string[] { "123", "345" })]
[TestCase("123 3.5 345", new string[] { "123", "345" })]
[TestCase("123 3. 345", new string[] { "123", "345" })]
[TestCase("123 .5 345", new string[] { "123", "345" })]
[TestCase(".5-1", new string[] { "-1" })]
[TestCase("0.5-1", new string[] { "-1" })]
[TestCase("3.-1", new string[] { "-1" })]
public void Regex(string input, string[] expected)
{
    Regex regex = new Regex(@"(?:(?<![.d])|-)d+(?![.d])");
    Assert.That(regex.Matches(input)
            .Cast<Match>()
            .Select(m => m.ToString())
            .ToArray(),
        Is.EqualTo(expected));
}

您可以使用:

(?<!.)-?bd+b(?!.)

工作示例

  • (?<!.) -号码前无句号。
  • -? -可选减号
  • bd+b -号码。用字边界包装,因此不可能在另一个数字中匹配(例如,在12345.6中不匹配1234)。2pi中的2不匹配。
  • (?!.) -号码后无句号。

试试这个:

    string pattern = @"((([d]+)/([d]+))*";
    string input = @"'((1/1000)*2375.50)'";

  foreach (Match match in Regex.Matches(input, pattern))
  {
     Console.WriteLine("{0}", match.Groups[1].Value);
     Console.WriteLine("{0}", match.Groups[2].Value);
  }         

最新更新