Grep正则表达式,用于可变长度的字符串中的数字

时间:2009-12-07 21:57:51

标签: regex shell grep

我需要一些方法来查找包含字符和数字组合的单词,但仅限4位数,并且至少包含一个字符。

实施例

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

9 个答案:

答案 0 :(得分:3)

要匹配grep中的数字,您可以使用[0-9]。要匹配除数字之外的任何内容,您可以使用[^ 0-9]。由于它可以是任意数量的,或者没有字符,因此您可以添加“*”(前面的任意数量)。所以你想要的是逻辑

(anything not a digit or nothing)* (any single digit) (anything not a digit or nothing)* . ...

直到你有4个“任何单个数字”组。即[^ 0-9] * [0-9] ......

我发现grep长图案,特别是需要转义的长串特殊字符,最好慢慢积累,这样你就可以确定你了解到底发生了什么。例如,

#this will highlight your matches, and make it easier to understand
alias grep='grep --color=auto'
echo 'a1b2' | grep '[0-9]' 

会告诉你它是如何匹配的。一旦理解了每个部件,就可以扩展模式。

答案 1 :(得分:2)

我不确定您可能采取的所有其他输入(即ax12ax12ax12ax12是否有效?),但这将根据您发布的内容生效:

%> grep -P "^(?:\w\d){4}$" fileWithInput

答案 2 :(得分:1)

如果你不介意使用一个小shell,你可以这样做:

echo "a1a1a1a1" |grep -o '[0-9]'|wc -l

将显示字符串中找到的位数。如果你愿意,你可以测试给定数量的匹配:

max_match=4
[ "$(echo "a1da4a3aaa4a4" | grep -o '[0-9]'|wc -l)" -le $max_match ] || echo "too many digits."

答案 3 :(得分:0)

使用grep

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

使用Perl以一种模式执行:

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

时髦的[^\W\d_]角色类是拼写[A-Za-z]的世界性方式:它捕获所有字母而不仅仅是英文字母。

答案 4 :(得分:0)

假设您只需要ASCII,并且只能访问grep的(相当原始的)正则表达式构造,则以下内容应非常接近:

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]

答案 5 :(得分:0)

您可以尝试

[^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*[0-9][^0-9]*

但是这将匹配1234.为什么不符合您的标准?

答案 6 :(得分:0)

正则表达式是:

([A-Za-z]\d){4}
  • [A-Za-z] - 用于角色等级
  • \ d - 编号
  • 你将它们包装在()中,将它们分组,表示格式字符后跟数字
  • {4} - 表示必须重复4次

答案 7 :(得分:0)

你可以使用普通的shell脚本,不需要复杂的正则表达式。

var=a1a1a1a1
alldigits=${var//[^0-9]/}
allletters=${var//[0-9]/}
case "${#alldigits}" in
   4)
    if [ "${#allletters}" -gt 0 ];then
        echo "ok: 4 digits and letters: $var"
    else
        echo "Invalid: all numbers and exactly 4: $var"
    fi
    ;;
   *) echo "Invalid: $var";;
esac

答案 8 :(得分:0)

感谢您的回答 最后我写了一些脚本,它完美无缺: 。 / P ab2b2 cd12 z9989 1ab26a9 1ab1c1 1234 24 a2b2c2d2

#!/bin/bash
echo "$@" |tr -s " " "\n"s >> sorting
cat sorting | while read tostr
do
  l=$(echo $tostr|tr -d "\n"|wc -c)
  temp=$(echo $tostr|tr -d a-z|tr -d "\n" | wc -c)

  if [ $temp -eq 4 ]; then
    if [ $l -gt 4 ]; then
      printf "%s " "$tostr"
    fi
  fi
done
echo