简体   繁体   中英

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

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)

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.

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. 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'".

NOTE : I tested it with LinqPad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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