Using Regular Expression in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gjain12
    New Member
    • Jun 2008
    • 19

    Using Regular Expression in java

    Hi All,

    I have a string in which I have to find all the commas except the one which is followed by "space". I have tried ",[^ ], but it finds the patterns that start with , and one character.
    e.g If my string is abc,bef, ghi,jkl,,mno
    the it returns ',b' ',j' and ',,' while I want only ',' so that it can search from the next element in the string. Means it should return ',' ',' ','.

    Thanks
    Gaurav
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Try the negative look behind pattern "(?<! ),";

    Comment

    • gjain12
      New Member
      • Jun 2008
      • 19

      #3
      Actually I am very novice to regular expression.
      If you can provide me some exampl sort of for the same, it will be really helpful.

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Now that I've read your post again I realize that you said followed by a space not preceded by a space.
        You need the negative look ahead instead.
        Code:
                        String p = ",(?! )";
        		String input = "abc,bef, ghi,jkl, ,mno";
        		Pattern pattern = Pattern.compile(p);
        		Matcher matcher = pattern.matcher(input);
        		boolean found = false;
        		while (matcher.find()) {
        			System.out.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", matcher.group(), matcher.start(), matcher.end());
        			found = true;
        		}
        		if (!found) {
        			System.out.format("No match found.%n");
        		}

        Comment

        • gjain12
          New Member
          • Jun 2008
          • 19

          #5
          Thanks a lot..
          It works perfectly...
          But I couldn't iunderstand how this regex is working.
          Means how should I read this expression.
          If you can explain it also it will be a great leraning experience.

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #6
            See the entries for those things in the regex tutorial.

            Comment

            Working...