1

I have a pattern that needs to be matched in a string and I'm unable to figure out the correct regex pattern.

A string may contain multiple matches of this pattern and I need the count of it.

  1. Starts with lowercase english letter.

  2. Zero or more occurances of any of these - lower english letters, digits and colons.

  3. one Forward slash - /

  4. Sequence of one or more lower case english letters and igits.

  5. one Backslash - \

  6. Sequence of one or more lower case english letters.

So far I've succeeded in writing this pattern as follows:

    Scanner sc=new Scanner(System.in);
    String line=sc.nextLine();
    String patern="(([a-z]+)([a-z0-9:]*)(\\/)([a-z0-9]+)(\\)([a-z]+))";
    Pattern r=Pattern.compile(patern);
    Matcher m=r.matcher(line);
    int count=0;
    while(m.find()) {       
        count+=1;
    }
    System.out.println(count);

But that's not giving me what I want. Any help from someone??

Sukumar
  • 171
  • 10

3 Answers3

1

Your regex works for your requirements, but you added \\ in (\\/) which you don't need.

You want the output to be 8, but there are 7 capturing group. You can get 8 if you also count the full match.

(([a-z]+)([a-z0-9:]*)(/)([a-z0-9]+)(\\\\)([a-z]+))

Regex demo

Demo Java

To get only the match without the grouping constructs you could use a more compact version and you might add anchors to match the start and the end of the string ^$

^[a-z][a-z0-9:]*/[a-z0-9]+\\[a-z]+$

In Java:

^[a-z][a-z0-9:]*/[a-z0-9]+\\\\[a-z]+$

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

following might help:

^[a-z]+[a-z0-9:]*\/[a-z0-9]+\\[a-z]+
Maroun
  • 94,125
  • 30
  • 188
  • 241
sacse
  • 3,634
  • 2
  • 15
  • 24
0

Here you go:

                Scanner sc=new Scanner(System.in);
                String line=sc.nextLine();
                String patern="^[a-z][a-z0-9:]*\\/[a-z0-9]+\\\\[a-z]+$";
                Pattern r=Pattern.compile(patern);
                Matcher m=r.matcher(line);
                int count=0, i=0;
                while(line.length()>i) 
                {
                    int j=0;
                    while(line.substring(i).length()>j)
                    {
                        if(m.find())
                        {
                            count+=1;
                            //System.out.println("at i="+i+"wher count="+count);
                        }
                        j++;
                        m=r.matcher(line.substring(i).substring(0,j));
                    }

                    i++;
                    m=r.matcher(line.substring(i));

                }
                List<String> li=new ArrayList<>();
                System.out.println(count);