regex 如何用正则表达式过滤出字符串

hec6srdp  于 2023-10-22  发布在  其他
关注(0)|答案(3)|浏览(140)

假设我想要一个正则表达式来表示一个过滤器,该过滤器只选择一个特定形状的字符串,如果它没有以特定的后缀结束,例如:

  • AaA.BbB.CcC.DdD.EeEa1.b2.c3.d4.e5都应通过过滤器

  • AaA.BbB.CcC.DdD.EeE.writinga1.b2.c3.d4.e5.writing不应该由于.writing后缀。

听起来像是[\d\w]!.writing的组合,但不确定如何在有效的正则表达式中表达这样的组合。
有人能帮帮忙吗?

nle07wnf

nle07wnf1#

你举的例子不太对。
[\d\w]冗余:\d[0-9],但\w已经与[a-zA-Z_0-9]匹配,
你说
AaA.BbB.CcC.DdD.EeE.writinga1.b2.c3.d4.e5.writing不应该由于.writing后缀。
现在如果你只关心它是否匹配,那么你可以检查是否有一个匹配的禁止结束和否定你下面的逻辑。

String inputString = <your-input>;
if( Pattern.compile("\\w*\\.writing$").matcher(inputstring).matches() ) {
 // no match - so the string is "valid"
}
hwamh0ep

hwamh0ep2#

可选正则表达式:
“^(?:\w+.)+\w+$”和“.writing$”
测试平台和上下文中的正则表达式:

public static void main(String[] args) {
    List<String> inputs = List.of("AaA.BbB.CcC.DdD.EeE", "a1.b2.c3.d4.e5", "AaA.BbB.CcC.DdD.EeE.writing", "a1.b2.c3.d4.e5.writing");

    for (String input: inputs) {
        printResult(input);
    }
}

private static void printResult(String input) {
    // Pattern allowedPattern = Pattern.compile("^(?:\\w+\\.)+\\w+$"); -> \\w will match 'A word character: [a-zA-Z_0-9]'
    // Pattern allowedPattern = Pattern.compile("^(?:[a-zA-Z0-9]+\\.){4}[a-zA-Z0-9]+$"); -> if you know that it always going to be 4 sections with ending dot, and the last section with no dot

    Pattern allowedPattern = Pattern.compile("^(?:[a-zA-Z0-9]+\\.)+[a-zA-Z0-9]+$");
    Pattern notAllowedSuffixPattern = Pattern.compile("\\.writing$");
    System.out.println("Incoming input: " + input);
    String result = (!notAllowedSuffixPattern.matcher(input).find() && allowedPattern.matcher(input).find())
            ? "Matching.\n"
            : "Not Matching!\n";
    System.out.println(result);
}

输出量:

Incoming input: AaA.BbB.CcC.DdD.EeE
Matching.

Incoming input: a1.b2.c3.d4.e5
Matching.

Incoming input: AaA.BbB.CcC.DdD.EeE.writing
Not Matching!

Incoming input: a1.b2.c3.d4.e5.writing
Not Matching!
t98cgbkg

t98cgbkg3#

grep

AaA.BbB.CcC.DdD.EeE
a1.b2.c3.d4.e5
AaA.BbB.CcC.DdD.EeE.writing

$ grep -v '.writing' file
AaA.BbB.CcC.DdD.EeE
a1.b2.c3.d4.e5

相关问题