Grep regular expression for digits in character st

2019-07-19 15:29发布

I need some way to find words that contain any combination of characters and digits but exactly 4 digits only, and at least one character.

EXAMPLE:

a1a1a1a1        // Match
1234            // NO match (no characters)
a1a1a1a1a1      // NO match
ab2b2           // NO match
cd12            // NO match
z9989           // Match
1ab26a9         // Match
1ab1c1          // NO match
12345           // NO match
24              // NO match
a2b2c2d2        // Match
ab11cd22dd33    // NO match

标签: regex shell grep
9条回答
We Are One
2楼-- · 2019-07-19 16:17

Assuming you only need ASCII, and you can only access the (fairly primitive) regexp constructs of grep, the following should be pretty close:

grep ^[a-zA-Z]*[0-9][a-zA-Z]*[a-zA-Z]*[0-9][a-zA-Z]*[a-zA-Z]*[0-9][a-zA-Z]*[a-zA-Z]*[0-9][a-zA-Z]*$ | grep [a-zA-Z]
查看更多
一纸荒年 Trace。
3楼-- · 2019-07-19 16:17

The regex for that is:

([A-Za-z]\d){4}
  • [A-Za-z] - for character class
  • \d - for number
  • you wrapp them in () to group them indicating the format character follow by number
  • {4} - indicating that it must be 4 repetitions
查看更多
狗以群分
4楼-- · 2019-07-19 16:23

With grep:

grep -iE '^([a-z]*[0-9]){4}[a-z]*$' | grep -vE '^[0-9]{4}$'

Do it in one pattern with Perl:

perl -ne 'print if /^(?!\d{4}$)([^\W\d_]*\d){4}[^\W\d_]*$/'

The funky [^\W\d_] character class is a cosmopolitan way to spell [A-Za-z]: it catches all letters rather than only the English ones.

查看更多
登录 后发表回答