有很多方法可以做到这一点。例如,您可以同时匹配 \d+ 和 \d+-\d+ ,然后只选择 \d+ 。虽然,我喜欢向前看和向后看的方法(注意:我引入了换行符和注释以提高可读性,它们应该是去除剂)
(?<!\d+-\d*) -- there is NO number in front
\d+ -- I AM THE number
(?!\d*-\d+) -- there is NO number behind
所以,你的正则表达式看起来像:
const string stuff = "Contract Nr.123456,reg.Nr.654321-118";
var rx = new Regex(@"(?<!\d+-\d*)\d+(?!\d*-\d+)");
Console.WriteLine(rx.Match(stuff).Value);
// result: 123456
或者,如果您想要字符串中的所有非连字符数字:
const string stuff = "Contract Nr.123456,reg.Nr.654321-118 and 435345";
var rx = new Regex(@"(?<!\d+-\d*)\d+(?!\d*-\d+)");
var m = rx.Match(stuff);
while (m.Success)
{
Console.WriteLine(m.Value);
m = m.NextMatch();
}
// result: 123456 and 435345
注意:下次尝试更具体,因为老实说,回答您提出的问题是“匹配'123456'的正则表达式是......'123456'”。
注意:我用 LinqPad 对其进行了测试。