Match a part of String using Reg Exp

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #1

    Match a part of String using Reg Exp

    Code:
    String input = "Mozila";
    System.out.println(Pattern.matches("^Moz")); //returns false
    System.out.println(Pattern.matches("^Moz.+")); //returns true
    Can't i match part of the string using Reg Exp?
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Interesting. I've never seen that before. Are you using capturing parentheses to get part of the match?
    Assuming you wanted .* as opposed to .+

    Comment

    • ahmee
      New Member
      • Mar 2010
      • 39

      #3
      there are different ways to go through a program....so go for the best u knwn

      Comment

      • ahmee
        New Member
        • Mar 2010
        • 39

        #4
        this is the code...

        import java.util.regex .*;
        class Strtok {

        public static void main(String [] args) {
        String s= "Why John Smith and Alan Smith and Nick gates";
        if(s.matches("W hy John Smith and Alan Smith and Nick gates"))
        {
        // System.out.prin tln(s.substring (4,14),s.substr ing(15,20));
        String substring = s.substring(3,1 5);
        String substring2 = s.substring(19, 29);
        String substring3 = s.substring(34, 44);
        System.out.prin tln(substring);
        System.out.prin tln(substring2) ;
        System.out.prin tln(substring3) ;
        }
        }
        }

        output

        John Smith
        Alan Smith
        Nick gates

        Comment

        • dmjpro
          Top Contributor
          • Jan 2007
          • 2476

          #5
          What does your code mean to me?

          Comment

          • jkmyoung
            Recognized Expert Top Contributor
            • Mar 2006
            • 2057

            #6
            Probably misposted from a similar but different thread.
            Assuming you are using a matcher, I would use parentheses to capture the input.
            Code:
            String input = "Mozila"; 
            Pattern pattern = Pattern.compile("^(Moz).*");
            Matcher matcher = pattern.matcher(input);
            while (matcher.find()){
                    	System.out.println(matcher.group(1)); //prints out Moz
            }
            Notice the use of 1 to get the first group as opposed to the entire match. Not entirely sure if this is what you want, but hope it leads you in the right direction.

            Comment

            Working...