Results 1 to 3 of 3
  1. #1
    flok is offline Member
    Join Date
    Sep 2009
    Location
    Gouda, the Netherlands
    Posts
    24
    Rep Power
    0

    Default regular expression matching does not work

    Hi,

    It seems either something's fishy with the Java regular expression implementation or my understanding of it.

    If I match "een" against "dit is een test" using the unix grep utility or using the perl scripting language, I get a match as "een" is part of "dit is een test".
    If I try to match these in Java, it doesn't! It seems I need to add ".*" to the beginning and the end of the matching-pattern. That is odd as I did not put a ^ in front or a $ behind my pattern.
    Example:

    Java Code:
    class regexptest
    {
            public static void main(String [] args)
            {
                    String input = "dit is een test";
                    String pattern1 = "een";
                    String pattern2 = ".*een.*";
    
                    System.out.println("pattern 1 matches: " + (input.matches(pattern1)));
                    System.out.println("pattern 2 matches: " + (input.matches(pattern2)));
            }
    }
    Now my question is: how do I get the normal regular expression behaviour in Java? (like grep/sed/awk and also perl somewhat does)

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,365
    Blog Entries
    7
    Rep Power
    20

    Default

    Read the API documentation for the Matcher class: you are trying to match the entire String against the regular expression (they are not equal of course). You need to use another method from that class.

    kind regards,

    Jos

  3. #3
    flok is offline Member
    Join Date
    Sep 2009
    Location
    Gouda, the Netherlands
    Posts
    24
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Read the API documentation for the Matcher class: you are trying to match the entire String against the regular expression (they are not equal of course). You need to use another method from that class.
    Found it! It is indeed the 'find()'-method.
    Thanks!

Similar Threads

  1. Java Regular Expression help
    By royalibrahim in forum Advanced Java
    Replies: 11
    Last Post: 11-12-2009, 01:27 AM
  2. regular expression
    By ras_pari in forum Advanced Java
    Replies: 27
    Last Post: 10-07-2009, 12:25 PM
  3. Complex Regular Expression HELP
    By hiklior in forum New To Java
    Replies: 1
    Last Post: 04-30-2008, 01:52 PM
  4. Replies: 0
    Last Post: 04-16-2008, 10:59 PM
  5. regular expressions and string matching
    By DennyLoi in forum New To Java
    Replies: 1
    Last Post: 11-16-2007, 10:15 AM

Posting Permissions

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