This discussion is archived
3 Replies Latest reply: Mar 21, 2013 8:48 AM by PhHein RSS

String parsing multichar combination

800839 Newbie
Currently Being Moderated
Hi,


I have string

String str= "BOBBBBB$@$CHANDLER!^~HARRY,JIM[]";

Here I need to parse the string and see whether there are "$@$"(combination) and "!^~" (combination)together, if both are there throw an exception else allow it.
The imp. thing here is both the multichar "$@$" and "!^~" should be displayed in the string as above as a combination, then only we need to validate and if both the combination are present throw an exception.

Please let me know how we can do it?

Thanks.
  • 1. Re: String parsing multichar combination
    PhHein Guru Moderator
    Currently Being Moderated
    Use a regular expression. http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
  • 2. Re: String parsing multichar combination
    800839 Newbie
    Currently Being Moderated
    Thanks. But we can form the pattern for the String?
               
    
                            String str="BOBBBBB$@$CHANDLER!^~HARRY,JIM[]";
                   String pattern = "......"; // how do the form the pattern for the above string(?)
                   Pattern p = Pattern.compile(pattern);
                   Matcher m = p.matcher(str);
         
              
                   if (m.matches()) {
                        for (int i = 0; i < m.groupCount(); i++)
                             System.out.println("Group" + i + ": " + m.group(i));
                   } else {
                        System.out.println("\"" + s + "\" did not match \"" + pattern + "\"");
                        System.out.println("so if I call m.group() it'll throw IllegalStateException !");
                   }
              }
    Please clarify.
  • 3. Re: String parsing multichar combination
    PhHein Guru Moderator
    Currently Being Moderated
    Id say something like this:
    ".*\\$@\\$.*!\\^~.*"
    But this only matches if the two patterns are in the correct order.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points