获取整数,排除十进制数,使用.NET正则表达式

5

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

我想要获取其中的 1 和 1000,它们是整数

我尝试了这个正则表达式:

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

我需要使用什么表达式来匹配(1 和 1000)?


你的所有输入字符串格式都是 ((x/y)*z) 吗? - Chrono
1
@Chrono:不,那只是一个示例字符串。任何字符串都可以。 - Bienvenido Omosura
3个回答

4
基本上,您需要匹配未前置或后置小数点或其他数字的数字序列?为什么不尝试只做这个呢?
[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));
}

看起来有效。


你的模式非常有效,适用于任何字符串。 - Bienvenido Omosura
@Bienvenido,首先,没必要大声喊叫。还有,正如Kobi指出的那样,我完全忘记了负号。请看我的编辑。 - Sergei Tachenov

3

您可以使用:

(?<!\.)-?\b\d+\b(?!\.)

工作示例

  • (?<!\.) - 数字前没有句号。
  • -? - 可选的减号。
  • \b\d+\b - 数字。用单词边界包裹,因此不可能在另一个数字内匹配(例如,不能在12345.6中匹配1234)。这不会匹配2pi中的2
  • (?!\.) - 数字后没有句号。

你的更好,因为你考虑到了减号和整数可能是标识符的一部分。 - Sergei Tachenov
@SergeyTachenov - 谢谢!减号是问题的一部分(所有模式都以“-?”开头)。2pi 的事情可能是我模式中的一个错误,我们可能想匹配这些整数。 - Kobi
1
啊,我在问题中漏掉了减号。现在已经修复了。顺便说一下,在这里你有一个 bug,对于像"3.-1"这样的字符串,你将不匹配"-1"。 - Sergei Tachenov
1
@Sergey - 可能吧。也许 3. 是一个有效的数字。也许 3.0-1 应该匹配到 1,而不是 -1(与 3.0*-1 相反)。这里没有足够的信息来进行规范说明 :P - Kobi

1
尝试这个:

Try this:

    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);

  }         

谢谢你的回答。我已经尝试了,但是模式匹配是((1/1000)*,我只想要1和1000。 - Bienvenido Omosura
你现在可以尝试一下。 - Mustofa Rizwan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接