• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Help with Greedy and Reluctant SCPJ 310 055

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi friends I have some misgivings with greedy and reluctant
in regex expersions . I ran this piece of code

import java.util.regex.*;
public class Music{
String s = " rap rapture wrap" ;
public static void main(String argv[]){
new Music();
}
Music(){
String regex = "r\\wp?";
Pattern pattern = Pattern.compile(regex);
Matcher matcher =pattern.matcher(s);
while(matcher.find()){
System.out.print(matcher.group());
}
}
}

and the output was rapraprerap with the greedy ? that means 0 o 1 character is reading from
left to right but the book say that greedy read all the string and begin from the end to the
begining.After that I modified the code with the reluctant operator as below


import java.util.regex.*;
public class Music{
String s = " rap rapture wrap" ;
public static void main(String argv[]){
new Music();
}
Music(){
String regex = "r\\wp??";
Pattern pattern = Pattern.compile(regex);
Matcher matcher =pattern.matcher(s);
while(matcher.find()){
System.out.print(matcher.group());
}
}
}

and the output was rararera . I am confused somebody can help me.
 
author
Posts: 23909
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

I am confused somebody can help me.



Quite frankly, I am not sure what you are asking here, as you don't seem to say what you are confused about... However...

There are two behaviors you need to keep track of. First, yes, in a greedy match, the regex will try to match as much as possible. And as the matches fail, it will back off until the match succeeds.

Second, and this is not related to greedy or reluctant, is how the find() method behaves. The find() method will try to match starting from the end of the last match, going forward, until it succeeds. And this is the behavior regardless of whether the regex is greedy or reluctant.

Henry
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic