Using Regular Expression (regex) in Java Programming

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lordelf007
    New Member
    • May 2010
    • 3

    #1

    Using Regular Expression (regex) in Java Programming

    Hiii all,

    I'm new in using Regular Expression in Java.

    For example, I have String s like this:

    String s = "Why John Smith and Alan Smith and Nick Gates are the same?"

    How can I get sub-strings as "John Smith", "Alan Smith", "Nick Gates" - (names of people - with first upper character) from s by using regex?

    I try to use regex in Java, but It totally doesn't work.

    This is my code:
    Code:
    /*
    String EXAMPLE_TEST = "Why John Smith and Alan Smith and Nick Gates are the same?";
    System.out.println(EXAMPLE_TEST.matches("([A-Z]&&[a-z])"));
    String[] splitString = (EXAMPLE_TEST.split("([A-Z]&&[a-z])"));
    System.out.println(splitString.length);
    for (String string : splitString) {
    System.out.println(string);
    }
    
    */

    Please help me to have exact "regex" in this case.

    Thanks all in advance!
    Last edited by Frinavale; May 13 '10, 01:44 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    I think it's something like:
    "\ ([A-Z][a-z]+\ [A-Z][a-z]+)"

    Added a space in the beginning so that you don't get "Why John" as your first match.

    Comment

    • lordelf007
      New Member
      • May 2010
      • 3

      #3
      hii jkmyoung,

      I tried your regex. It seems to be worked, but It just prints out other words like this:
      "Why,
      and,
      and,
      are the same ?"

      Can I print these words: "John Smith", "Alan Smith", "Nick Gates" ?

      Comment

      • lordelf007
        New Member
        • May 2010
        • 3

        #4
        thanks jkmyoung very much!

        I figured out by using matcher.group() :

        Pattern pattern = Pattern.compile (" [A-Z][a-z]+ [A-Z][a-z]+");
        Matcher matcher = pattern.matcher ("Why John Smith and Alan Smith and Nick Gates are the same?");
        while( matcher.find() )
        System.out.prin tln("main: "+matcher.group ());

        Comment

        • pbrockway2
          Recognized Expert New Member
          • Nov 2007
          • 151

          #5
          If this is anything other than homework then you're going to have problems with the likes of Old MacDonald, Rip van Winkle and Stephen J Gould.

          Comment

          Working...