简体   繁体   中英

Regex to Match only integer

As title says, I am trying to build a regex to extract integer number from a string. The actual scenario is, I am having a very large file of codes (the integers) and some values (decimals).

I can successfully extract the decimals with [\\d]*([.,][\\d]*) . (It may seem strange but I am also capturing .1 or 1.). However I cannot extract the integers, until now I have something like [\\d]*([\\d]*)[\\d] . I also tried something like ^[\\d]+$ but with no luck.

I will use this regex in a C# application, so I do not know if any additional 'rules' apply.

Regex ex = new Regex(@"MY_REGEX", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);

This is possibly a duplicate, however I cannot figure it out.

Having the

0066 435sxxzx 23454 2 3 45 06 11.3243 sds435 adc234wer

I am trying to match only

0066 23454 2 3 45 06

Here is an example in regex101

Make sure there are no decimal separators on both ends with lookarounds:

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

See the regex demo

C# (you do not seem to need the ignore case flag as . and digits do not have case variants):

var ex = new Regex(@"\b(?<!\.)\d+(?!\.)\b", RegexOptions.CultureInvariant);

The regex breakdown:

  • \\b - word boundary (we require the character before the number to be a non-word char or the beginning of a string
  • (?<!\\.) - this char cannot be a dot
  • \\d+ - match 1+ digits...
  • (?!\\.) - only if not followed with a .
  • \\b - but there must be a non-word char or the end of string.

在此处输入图片说明

This was too long for a comment, but just a suggestion: if the goal is obtaining the integer values themselves, rather than the text, you could use int.TryParse on each 'word' instead of regex. In a linq format:

string input = "0066 435sxxzx 23454 2 3 45 06 11.3243 sds435 adc234wer";

var ints = input.Split(' ')
    .Select(s=> {int i; if(int.TryParse(s,out i))return i; else return (int?)null;})
    .Where(i=>i.HasValue)
    .ToList();

split the string by spaces.

For example in java:

String parts[] = text.split(" ");

Than you can check every word if it is a number with regex or by parsing it as a number.

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