Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Doubt related to regex

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

This is a question from K&B master exam

import java.util.regex.*;
class Regex2{
public static void main(String args []){
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]);
boolean b = false;
while (b = m.find()) {
System.out.println(m.start() + m.group() + "");
}
}
}


And the invocation java Regex2 "\d\s\w" "12s 4 w 33 1"

produces the output 44 w and 93 1

Now,since the 2 groups found are "4 w" and "3 1",i understand that the first part of the output is "44 w".
Along the same lines,the 2nd part of the output should have been "33 1".
can someone explain how is it "93 1"?

Thanks,
Aditi.
 
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.out.println(m.start() + m.group() + "");

Is it because the start() index is also printed prefixing m.group()?
 
author
Posts: 23919
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Along the same lines,the 2nd part of the output should have been "33 1".
can someone explain how is it "93 1"?



Because "3 1" is at index location 9. My question is, why do you think it should be at index location 3?

Henry
 
Aditi Roychoudhury
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Henry and Byju,

Thanks a lot for your answers.
I was thinking that the start() method returns the first element of the group.I was obviously wrong.Thanks again.

Thanks,
Aditi
 
when your children are suffering from your punishment, tell your them it will help them write good poetry when they are older. Like this tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic