Results 1 to 5 of 5
  1. #1
    hadi is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default A Question Regarding Pattern Matching

    Hello
    I want to extract words from a string followed by a - .
    for example in string : "sss-ddd-fff-" , i want the following groups :
    1- "sss-"
    2- "ddd-"
    3- "fff-"

    I wrote this regex for doing this : "((?:[^-]+)-)+"
    But this isn't working as i said .
    Could you explain what regex should i write for the mentioned task ? and what is the meaning of my
    regex ?

    thanks

  2. #2
    JavaHater is offline Senior Member
    Join Date
    Dec 2010
    Posts
    165
    Rep Power
    4

    Default

    in this simplest sense , you can just use this pattern
    Java Code:
    Pattern.compile("\\w+-");

  3. #3
    hadi is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default

    That pattern doesn't capture any groups , i want groups like i said .

  4. #4
    JavaHater is offline Senior Member
    Join Date
    Dec 2010
    Posts
    165
    Rep Power
    4

    Default

    Java Code:
    public class StringDemo{
        private static Pattern ex = Pattern.compile("\\w+-");
        private static Matcher match;
        public static void main(String[] args){
            String str = "sss-ddd-fff-";
            match = ex.matcher(str);
            while ( match.find() ){
                 System.out.println( match.group()) ;
             }
        }
    }
    output
    Java Code:
    $ java StringDemo
    sss-
    ddd-
    fff-

  5. #5
    hadi is offline Member
    Join Date
    Jan 2011
    Posts
    5
    Rep Power
    0

    Default

    OK thanks javahater
    match.groupCount(); was giving me 0 and i thought it didn't found any matches

Similar Threads

  1. pattern matching with two arrays
    By jessie in forum New To Java
    Replies: 10
    Last Post: 11-24-2010, 04:00 PM
  2. Replies: 0
    Last Post: 06-29-2010, 08:16 PM
  3. String matching a pattern
    By vividcooper in forum New To Java
    Replies: 7
    Last Post: 01-07-2010, 10:30 PM
  4. Replies: 1
    Last Post: 10-27-2009, 07:33 PM

Tags for this Thread

Posting Permissions

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