正则表达式仅匹配整数 [英] Regex to Match only integer

查看:76
本文介绍了正则表达式仅匹配整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,我正在尝试构建一个正则表达式来从字符串中提取整数.实际情况是,我有一个很大的代码文件(整数)和一些值(十进制).

我可以使用 [\ d] *([.,] [\ d] *)成功提取小数.(这可能看起来很奇怪,但我也在捕获.1或1.).但是我无法提取整数,直到现在我有了 [\ d] *([\ d] *)[\ d] 之类的东西.我也尝试了类似 ^ [\ d] + $ 的方法,但是没有运气.

我将在C#应用程序中使用此正则表达式,因此我不知道是否还有其他规则".

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

这可能是重复的,但是我无法弄清楚.

拥有

 <代码> 0066 435sxxzx 23454 2 3 45 06 11.3243 sds435 adc234wer 

我只尝试匹配

 <代码> 0066 23454 2 3 45 06 

以下是

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.

这篇关于正则表达式仅匹配整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆