【问题标题】:How to match generic string = generic string如何匹配通用字符串=通用字符串
【发布时间】:2018-02-07 09:53:03
【问题描述】:

假设我有这个文件:

AND 1=1
AND fejo = fejo
AND 4=5
AND 423=523

我想匹配=左侧的行与=符号右侧的行相同,因此,它必须匹配以下行:

AND 1=1
AND fejo = fejo

【问题讨论】:

  • 你是Linux系统吗?

标签: regex grep string-parsing


【解决方案1】:
grep -E '^AND\s+([^=\s]*)\s*=\s*\1\b'

与您的输入配合得很好。

正则表达式

^               # begin of line (preg tries to match the regex against each line)
AND             # match literal 'AND'
\s+             # match one or more whitespace characters
(               # beginning of a group
    [           # beginning of a character class that...
        ^       #    ... match any character that is not listed here:
        =       #    literal '='
        \s      #    whitespace
    ]           # end of the character class...
                # ... that matches one character that is not '=' or whitespace
    *           # zero or more occurrences of the previous expression (the class)
)               # end of the capturing group
\s*             # match zero or more spaces... 
=               # the '=' character
\s*             # ... around the equal sign
\1              # match the text captured by the first (and only) group above
\b              # match a word boundary, to make sure \1 is not just a prefix of a longer word

上面的regex 只匹配以大写AND 开头的行。如果您还需要匹配以and(小写)或这些字符的其他大小写组合开头的行,您可以将regex 中的AND 替换为[aA][nN][dD]

-i 添加到grep 命令行使其忽略regex 和输入中的大小写。 regex 将匹配 and 1 = 1 但也匹配 and fejo = FEJO,这可能不是您需要的。

【讨论】:

  • 可能在末尾添加一个$ 锚点,以确保右边的不是前缀匹配(以匹配开头的较长字符串)。
  • \s 不可移植;也许改用 POSIX [[:space:]]
【解决方案2】:

使用 awk:

$ awk 'split($0,a," *= *") && a[1]==($1 " " a[2])' file
AND 1=1
AND fejo = fejo

split= 上的记录拆分为AND 11,在a[2]1 前面添加$1AND 并进行比较。如果$1 之后的空间超过空间,则会失败。为避免这种情况,这似乎也有效:

$ awk 'split($0,a,"( *= *| *)") && a[2]==a[3]' file
AND 1=1
AND fejo = fejo

缺点是被比较的元素中不能有空间。这个清除了第一个单词及其周围的空间,śplits =(包括周围的空间)并比较了一半。

$ awk ' {
    r=$0                     # working copy of record
    sub(/^ *[^ ]* */,"",r)   # remove AND
    n=split(r,a," *= *")     # split at = 
    if((n>1)&&a[1]==a[n])    # if r was really split in half and halfs match
        print
}' file
AND 1=1
AND fejo = fejo

【讨论】:

    【解决方案3】:

    我找到了另一个非常简单的解决方案,而不必弄得一团糟:

    AND (\w+)\s*=\s*\1

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 2017-10-28
      • 1970-01-01
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多