We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Regular Expressions syntax
Page Index Toggle Pages: 1
Regular Expressions syntax (Read 787 times)
Regular Expressions syntax
Feb 27th, 2009, 3:20am
 
hi, i'm new to regex's and i can't figure out how to write the syntax to find ONLY the word that follows the word "red" when found in a sentence.

for example, the string "Short red hair and some freckles." should return the word "hair".

my code below returns "red hair and some freckles."
Pattern redwordpattern = Pattern.compile("\\b(red)(.*)", Pattern.CASE_INSENSITIVE);

can someone explain to me why this is? thanks in advance!

i've  been using this as reference:
http://www.shiffman.net/teaching/a2z/regex/#regex
Re: Regular Expressions syntax
Reply #1 - Feb 27th, 2009, 8:37am
 
String s = "Short red hair and some freckles.";
String[] m = match(s, "\\bred\\s*(\\w+)");
println("Found '" + m[1] + "'");

If you need to include ' and - for example, use:
"\\bred\\s*([\\w'-]+)"
Re: Regular Expressions syntax
Reply #2 - Feb 27th, 2009, 9:26am
 
thanks!

both
Pattern redwordpattern = Pattern.compile("\\bred\\s*(\\w+)", Pattern.CASE_INSENSITIVE);  
&
Pattern redwordpattern = Pattern.compile("\\bred\\s*([\\w'-]+)", Pattern.CASE_INSENSITIVE);
work.

it's still printing the word "red hair" instead of just "hair". could it be the group() i'm using?

while(redwordmatcherDescrip.find()){
     s+="Description color word:" + redwordmatcherDescrip.group() + newline;
   }


thanks again!


Re: Regular Expressions syntax
Reply #3 - Feb 27th, 2009, 12:49pm
 
Note I used Processing's match which wraps Pattern and Matcher stuff.

And indeed, group 0 stands for the entire expression while group 1 is the first (and only, here) capture.
Re: Regular Expressions syntax
Reply #4 - Feb 27th, 2009, 8:56pm
 
awesome. i didn't know you do matcher and pattern stuff with just "match" in processing. that's cool.

i've been using them separately:

Pattern redpattern = Pattern.compile("\\b(red)\\b", Pattern.CASE_INSENSITIVE);

Matcher redmatcherDescrip = redpattern.matcher(description);

thanks again!
Page Index Toggle Pages: 1