codd
codd

Reputation: 55

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.

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.

Upvotes: 0

Views: 210

Answers (2)

Aerospace
Aerospace

Reputation: 1270

\\s+ or \\s* missing

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:

20258044753052856   A security  cvvc    TagTitle

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174874

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.

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

Upvotes: 1

Related Questions