简体   繁体   English

正则表达式:未找到匹配项

[英]Regular Expression : No match found

I just started learning about regular expressions. 我刚刚开始学习正则表达式。 I am trying to get the attribute values within "mytag" tags and used the following code, but it is giving me No match found exception. 我正在尝试获取“ mytag”标签内的属性值,并使用了以下代码,但它给我没有找到匹配的异常。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class dummy {

    public static void testRegEx()
    {
    //  String pattern_termName = "(?i)\\[.*\\]()\\[.*\\]";

        Pattern patternTag;
        Matcher matcherTag;

        String mypattern= "\\[mytag attr1="(.*?)" attr2="(.*?)" attr3="(.*?)"](.+?)\\[/mytag]";

        String term="[mytag attr1=\"20258044753052856\" attr2=\"A security \" attr3=\"cvvc\" ]TagTitle[/mytag]";


        patternTag = Pattern.compile(mypattern);

        matcherTag = patternTag.matcher(term);

        System.out.println(matcherTag.group(1)+"*********"+matcherTag.group(2)+"$$$$$$$$$$$$");
    }

    public static void main(String args[])
    {
        testRegEx();    
    }

}

I have used \\" in place of " but it still shows me same exception. 我用\\"代替"但它仍然显示相同的异常。

You forget to check the matcher object against find function and also you need to use \\" instead of " ,. The find method scans the input sequence looking for the next subsequence that matches the pattern. 您忘记对照find函数检查匹配器对象,并且还需要使用\\"而不是" 。find方法扫描输入序列以查找与该模式匹配的下一个子序列。

Pattern patternTag;
Matcher matcherTag;
String mypattern= "\\[mytag attr1=\"(.*?)\" attr2=\"(.*?)\" attr3=\"(.*?)\"\\s*](.+?)\\[/mytag]";
String term="[mytag attr1=\"20258044753052856\" attr2=\"A security \" attr3=\"cvvc\" ]TagTitle[/mytag]";
patternTag = Pattern.compile(mypattern);
matcherTag = patternTag.matcher(term);
while(matcherTag.find()){
       System.out.println(matcherTag.group(1)+"*********"+matcherTag.group(2)+"$$$$$$$$$$$$");
}

Output: 输出:

20258044753052856*********A security $$$$$$$$$$$$

DEMO DEMO

\\\\s+ or \\\\s* missing 缺少\\\\s+\\\\s*

code: 码:

final String  pattern = "\\[\\s*mytag\\s+attr1\\s*=\\s*\"(.*?)\"\\s+attr2\\s*=\\s*\"(.*?)\"\\s+attr3\\s*=\\s*\"(.*?)\"\\s*\\](.+?)\\[/mytag\\]";
final String  input   = "[mytag attr1=\"20258044753052856\" attr2=\"A security \" attr3=\"cvvc\" ]TagTitle[/mytag]";
final Pattern p = Pattern.compile( pattern );
final Matcher m = p.matcher( input );
if( m.matches()) {
   System.out.println(
      m.group(1) + '\t' + m.group(2) + '\t' + m.group(3) + '\t' + m.group(4));
}

outpout: outpout:

20258044753052856   A security  cvvc    TagTitle

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

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