Results 1 to 2 of 2
  1. #1
    Webwizard is offline Member
    Join Date
    Apr 2013
    Posts
    1
    Rep Power
    0

    Default Java Regex capturing group question

    Hi everyone,
    my question is in regard to Java Regex and capturing groups:

    When a capturing group doesn't match, the group normally gives a "null" response when called with mymatcher.group(groupnumber).

    However, when I have the following:

    Pattern testPattern = Pattern.compile("(\\d*)([^{]*)");
    Matcher m2 = testPattern.matcher("1234");

    When I println it, m2.group(1) will return "1234" as expected.
    But m2.group(2) will not return null, but empty ""

    I guess it's because of the exclusion pattern [^{]*
    Does anyone know how to get around it and get the "null" I am looking for?

    Thanks!

    W

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Java Regex capturing group question

    It makes sense that zero-or-more of something matches an empty string. Would it meet your requirements to replace "[^{]*" with "[^{]+"? Alternatively, why can't you test for an empy string in the same place you're presumably testing for null?
    Get in the habit of using standard Java naming conventions!

Similar Threads

  1. How Capturing Sound Mic & Speaker with Java
    By FJavierBG in forum New To Java
    Replies: 2
    Last Post: 08-21-2012, 05:03 AM
  2. Beginner's JAVA Group
    By spect4cle in forum Forum Lobby
    Replies: 0
    Last Post: 11-06-2011, 03:02 AM
  3. regex question
    By jruland in forum Advanced Java
    Replies: 5
    Last Post: 10-06-2010, 08:26 PM
  4. regex question
    By mac in forum New To Java
    Replies: 6
    Last Post: 03-17-2010, 06:57 AM
  5. Java Swing class capturing output to the console
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 03-12-2008, 12:24 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •