繁体   English   中英

Java Regex:匹配字符串中所有重复出现的序列

[英]Java Regex: match all reocurring sequences in a string

我阅读了一些示例以匹配字符串中所有出现的序列,但在此示例中遇到了一些困难。 我想按以下方式匹配表达式:

"test"-a-"test2"-b-"test3" ...//can alternate like this for any number of times

当我在上面的示例中测试代码时,它可以工作,但是当我尝试以下示例时,它告诉我匹配成功,但我不希望它成功。

"test"-a-"test2"-b"test3"  //this is successful but I want it to fail

我正在使用的正则表达式是:

^ ( ( \ " ( . * ) ? \ " ) * \ \  - ( [ a - z ] ) \ \ - \ " ( . * ) ? \ " ) + $ ;

您可以使用此正则表达式

Pattern p = Pattern.compile("^(\"[^\"]+?\"-[a-z]-)+\"[^\"]+?\"$");

如您所说:“它以带引号的字符串开头,然后是一个带有减号的小写字母,并且必须以带引号的字符串结尾”。

试试这个。

    String[] str = new String[] { "\"test\"-a-\"test2\"-b-\"test3\"",
                                  "\"test\"-a-\"test2\"-b\"test3\"", 
                                  "\"test\"-a-\"test2\"b\"test3\"" };

    // quote then one or more lower letter quote - one lower letter - <same pattern till the end>
    Pattern p = Pattern.compile("^(\"[a-z]+\"-[a-z]-\"[a-z]+\\d\"-[a-z]-\"[a-z]+\\d\")$");

    for (String s : str) {
        Matcher m = p.matcher(s);
        System.out.println(s + (m.find() ? " found" : " not found"));
    }

输出:

    "test"-a-"test2"-b-"test3" found
    "test"-a-"test2"-b"test3" not found
    "test"-a-"test2"b"test3" not found

您可以使用此:

String t = ...;
Pattern p = Pattern.compile( "\"[^\"]+?\"(?:-[a-z]-\"[^\"]+?\")+" );
Matcher m = p.matcher( t );
if( m.matches() ){
  // OK
} else {
  // not OK
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM