Match digits in [g]awk

坚强是说给别人听的谎言 提交于 2019-12-20 03:46:08

问题


I'm stumped! Trying to write an awk regex to match a string against 11 digits.

I've tried:

if (var ~ /^[0-9]{11}$/ )
if (var ~ /^([0-9]){11}$/ )
if (var ~ /^([0-9]{11})$/ )
if (var ~ /^[0-9]{11}/ ) # altho I really do need to check the whole str
if (var ~ /[0-9]{11}/ )

If I use this....

if (var ~ /^[0-9]+/ ) 

Then I get a match - but I need to check for exactly 11 digits.


回答1:


You described your problem, but didn't tell us your awk version. It is an important information.

but this may work for your case:

if (var ~ /^[0-9]+$/ && length(var)==11)

If we know the version, there could be simpler solution.




回答2:


If you are trying to match exactly 11 consecutive digits someplace in the string:

Using the test file:

hi12345678910
hi1234

The windows version of awk command line:

awk --posix "{ if ($1 ~ /[0-9]{11}/) print}" testfile.txt

It printed:

hi12345678910



回答3:


Doh - forgot to RTM:

              Interval expressions are only available if either --posix or
              --re-interval is specified on the command line.


来源:https://stackoverflow.com/questions/16088141/match-digits-in-gawk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!