我有一个示例字符串'((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
)?
[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));
}
看起来有效。
您可以使用:
(?<!\.)-?\b\d+\b(?!\.)
(?<!\.)
- 数字前没有句号。-?
- 可选的减号。\b\d+\b
- 数字。用单词边界包裹,因此不可能在另一个数字内匹配(例如,不能在12345.6
中匹配1234
)。这不会匹配2pi
中的2
。(?!\.)
- 数字后没有句号。2pi
的事情可能是我模式中的一个错误,我们可能想匹配这些整数。 - Kobi3.
是一个有效的数字。也许 3.0-1
应该匹配到 1
,而不是 -1
(与 3.0*-1
相反)。这里没有足够的信息来进行规范说明 :P
。 - Kobi 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
((x/y)*z)
吗? - Chrono