仅当文本不包含其他字符串时才匹配字符串

时间:2019-03-26 16:39:50

标签: regex

我有以下用例。如果字符串的一部分不包含其他字符串,则我需要一个正则表达式模式仅匹配一行。这是一个示例:

<androidx.constraintlayout.widget.Barrier
        android:id="@+id/barrier6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="12dp"/>

所以在这里我要匹配android:layout_marginStart="12dp",以便可以替换为:

android:layout_marginStart="12dp"
android:layout_marginLeft="12dp"

我已经解决了这个问题,可以使用以下正则表达式来做到这一点:

查找:(.*)android:layout_marginStart="(.*)" 替换:$1android:layout_marginStart="$2"\n$1android:layout_marginLeft="$2"

我不能做的是有条件的比赛。如果此xml对象已经包含android:layout_marginLeft属性,我就不想匹配。

1 个答案:

答案 0 :(得分:1)

在正则表达式中,如果要检查以确保在想要匹配的部分之后没有出现字符串,则可以使用负前瞻。

在此示例中,您希望匹配某些内容,但前提是字符串layout_marginLeft稍后不再出现。您可以这样做,但是将layout_marginLeft置于负面的前瞻状态,如下所示:

(?:(?!layout_marginLeft).)*

现在,当您将其与实际要匹配的正则表达式结合使用时,将看起来像这样:

(android:layout_marginStart="(.*?)")(?:(?!layout_marginLeft).)*(?=/>)

然后您的替换字符串如下所示:

\1\n\t\tandroid:layout_marginLeft="\2"

因此,替换内容的工作方式相同,只是您要告诉它不要对已经包含layout_marginLeft的任何内容进行替换。

Here is a demo

相关问题