简体   繁体   English

查找数字的字符串正则表达式

[英]string Regex that finds digits

I`m having problems with Regex. 我正则表达式遇到问题。 I have a line Collapse | 我有一行折叠| Copy Code 复制代码

Contract Nr.123456,reg.Nr.654321-118 合同Nr.123456,reg.Nr.654321-118

I want to use a regex that Finds only the string 123456, but doesn't find the second 6 digit- 3 digit string(654321-118) 我想使用仅查找字符串123456但找不到第二个6位数-3位数字符串的正则表达式(654321-118)

This is what i came up with, but don't really know what to do next Collapse | 这是我想出的,但我真的不知道下一步该怎么做。 Copy Code 复制代码

string regex4 = @"\d{4,6}[^-]";

Any Ideas? 有任何想法吗? Thank you. 谢谢。

---the comma isn't specific, I think I need to build the regex so It didn't find strings that end with the "-" sign ---逗号不是特定的,我想我需要构建正则表达式,因此它找不到以“-”符号结尾的字符串

---This is payment details in the bank, field-recievers info. ---这是银行中的付款明细,现场收款人信息。 There are two possible sets of digits xxxxxx and xxxxxx-xxx, I need to find only the first one. 有两种可能的数字集xxxxxx和xxxxxx-xxx,我只需要找到第一个。

A bit crude but if it's pure numbers only you are concerned about and only the first occurance of it then you can do something simple like, 有点粗糙,但是如果它只是纯数字,那么您只需要关心它,并且只有它的首次出现,那么您可以做一些简单的事情,

const string stuff = "Contract Nr.123456,reg.Nr.654321-118";

var regex = new Regex(@"\d+");

Console.WriteLine(regex.Match(stuff).Value);

There are many ways you could do this. 您可以通过多种方式执行此操作。 For example you could match both \\d+ and \\d+-\\d+ and THEN select only \\d+ ones. 例如,您可以同时匹配\\ d +和\\ d +-\\ d +,然后仅选择\\ d +。 Although, I like look-ahead and look-behind approach (note: I introduced line breaks and comments for readability, they should be remover) 虽然,我喜欢先行和后进的方法(注意:我引入了换行符和注释以提高可读性,但应该将其删除)

(?<!\d+-\d*) -- there is NO number in front
\d+          -- I AM THE number
(?!\d*-\d+)  -- there is NO number behind

so, your regex looks like: 因此,您的正则表达式如下所示:

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

or, if you want all non-hyphenated numbers in string: 或者,如果要在字符串中使用所有非连字符的数字:

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

NOTE : And next time try to be more specific because, to be honest, answer to the question you asked is "regular expression which matches '123456' is... '123456'". 注意 :下次尝试更加具体,因为老实说,回答您的问题是“与'123456'匹配的正则表达式为...'123456'”。

NOTE : I tested it with LinqPad. 注意 :我使用LinqPad对其进行了测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM