正则表达式匹配大括号之间的特定字符串

时间:2021-06-01 01:43:23

标签: regex kotlin

我将 css 作为字符串,如下所示

    .c8450 {
    color: #000000; font-family: TsukuMin,TsukuMin,TsukuMin,TsukuMin; font-size: 18px; line-height: 1.6em;
    }
    .c8451 {
    text-indent: -4em; text-align: left; min-width: 1.6em; border-top: solid transparent 4em;
    }
.c8451 {
    text-indent: -4em; text-align: left; min-width: 1.6em; border-top: solid transparent 4em; text-align-last:auto;
    }

如果它包含 text-align 属性但不包含 text-align-last 属性,我需要在两个大括号之间找到匹配项,所以我应该能够匹配第二组大括号,以便它返回< /p>

{text-indent: -4em; text-align: left; min-width: 1.6em; border-top: solid transparent 4em;}

我可以使用 \{+([^}]+)}+ 找到大括号之间的匹配项,并使用 text-align:(.*); 找到 text-indent 属性,但我不确定如何将两者结合起来以匹配此特定条件。< /p>

1 个答案:

答案 0 :(得分:0)

试试这个

fun main() {
    val text = """
        .c8450 {
            color: #000000; font-family: TsukuMin,TsukuMin,TsukuMin,TsukuMin; font-size: 18px; line-height: 1.6em;
        }
        .c8451 {
            text-indent: -4em; text-align: left; min-width: 1.6em; border-top: solid transparent 4em;
        }
        .c8451 {
            text-indent: -4em; text-align: left; min-width: 1.6em; border-top: solid transparent 4em; text-align-last:auto;
        }
    """
    val pattern = "\\{(.|\\r?\\n)*?\\}".toRegex()
    val matches = pattern.findAll(text)
    val list: MutableList<String> = mutableListOf()
    matches.forEach { f ->
        val value = f.value
        val pe = "text-align".toRegex();
        val pne = "text-align-last".toRegex()
        
        if(pe.containsMatchIn(value) && !pne.containsMatchIn(value)){
            list.add(value)
        }
    }
    
    print(list)
}

输出

[{
        text-indent: -4em; text-align: left; min-width: 1.6em; border-top: solid transparent 4em;
}]