匹配条件块

丹尼尔·B

我需要一些正则表达式大师帮助。

我正在尝试为家庭项目制作一个小型配置系统,但是为此,我似乎需要比我的regexp技能更多的regexp代码。

我需要能够根据条件和动作在块内提取一些信息。举个例子。

action1 [condition1 condition2 !condition3] {
    Line 1
    Line 2
    Line 3
}

条件存储在以空格分隔的简单变量中。我使用这些变量来创建用于从文件中提取块信息的regexp。如果我不知道如何制作“不匹配”部分,那基本上可以正常工作,这基本上意味着条件变量中没有“单词”。

VAR1="condition1 condition2"
VAR2="condition1 condition2 condition3"

与上面的条件匹配时,它应与VAR1匹配,但不匹配VAR2。

这就是我到目前为止

PARAMS="con1 con2 con3"
INPUT_PARAMS="[^!]\\?\\<$(echo $PARAMS | sed 's/ /\\>\\|[^!]\\?\\</g')\\>"

sed -n "/^$ACTION[ \t]*\(\[\($INPUT_PARAMS\)*\]\)\?[ \t]*{/,/}$/p" default.cfg | sed '/^[^{]\+{/d' | sed '/}/d'

不知道这有多漂亮,但是除了不匹配之外,它确实可以工作。

编辑:

好吧,我会尝试详细说明。

假设我有以下text / config文件

action1 [con1 con2 con3] {
    Line A
    Line B
}

action2 [con1 con2 !con3] {
    Line C
}

action3 [con1 con2] {
    Line D
}

action4 {
    Line E
}

而且我有条件可以与之抗衡

ARG1="con1 con2 con3"
ARG2="con1 con2"
ARG3="con1"
ARG4="con1 con4"

# Matching against ARG1 should print Line A, B, D and E
# Matching against ARG2 should print Line C, D and E
# Matching against ARG3 should print Line E
# Matching against ARG4 should print Line E

下面是使用常规条件检查的类似于action2的Java示例。它可以更好地说明我在尝试什么

if (ARG2.contains("con1") && ARG2.contains("con2") && !ARG2.contains("con3")) {
    // Print all lines in this block
}
埃德·莫顿

我不知道如何选择要从中打印行的记录的逻辑,因此这是使用awk创建正值和负值条件集的方法:

$ cat tst.awk
BEGIN{
    RS = ""; FS = "\n"

    # create the set of the positive conditions in the "conds" variable.
    n = split(conds,tmp," ")
    for (i=1; i<=n; i++)
        wanted[tmp[i]]
}
{
    # create sets of the positive and negative conditions
    # present in the first line of the current record.
    delete negPresent   # use split("",negPresent) in non-gawk
    delete posPresent
    n = split($1,tmp,/[][ {]+/)
    for (i=2; i<n; i++) {
        cond = tmp[i]
        sub(/^!/,"",cond) ? negPresent[cond] : posPresent[cond]
    }

    allPosInWanted = 1
    for (cond in posPresent)
        if ( !(cond in wanted) )
            allPosInWanted = 0

    someNegInWanted = 0
    for (cond in negPresent)
        if (cond in wanted)
             someNegInWanted = 1

    if (allPosInWanted && !someNegInWanted)
        for (i=2;i<NF;i++)
            print $i
}

$ awk -v conds='con1 con2 con3' -f tst.awk file
    Line A
    Line B
    Line D
    Line E
$
$ awk -v conds='con1 con2' -f tst.awk file
    Line C
    Line D
    Line E
$
$ awk -v conds='con1' -f tst.awk file
    Line E
$
$ awk -v conds='con1 con4' -f tst.awk file
    Line E
$

现在,您只需要在完成打印的最终块中编写所需的逻辑代码,即可比较每个组中的条件。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章