Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regex doubt

 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i want to check if a text field has something like a >=2000 year:
2004 or
2004/2005, for example. (both are aceptable)
i'm using this code:

I've two Qs:
1) can i improve the regex expression?
2) how can i garantee, with regex, that user is writting, for example, 2004/2005 and not 2004/2003?
Thanks in advance
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



2) how can i garantee, with regex, that user is writting, for example, 2004/2005 and not 2004/2003?


You can't. (Well, you could by simply iterating all possible combinations, but I guess that doesn't qualify as a reasonable solution...)
[ October 08, 2004: Message edited by: Ilja Preuss ]
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
20\\d{2}

it's a good improvement
Thanks a lot!
 
Carol Enderlin
drifter
Ranch Hand
Posts: 1364
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure about your exact requirement, but if it is important that one matched value is "less" than the other (2004 < 2005)...

You can get the value that matched using the java.util.regex classes. I found a simple example in
Sun's regex tutorial.

In their simple example they are just printing them out using find() to try to match and group() to get back what matched:

 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Carol, good point!

 
Ian Darwin
author
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if (sepoca.matches(regex)) {
return true;
}
return false;

This segment is a bit like
if (true) {
return true;
} else {
return false;
}

And when you see it that way you realize that it lacks expressiveness.

You should probably just say:
return sepoca.matches(regex);

which is a complete statement that does the same thing.

Ian

"Brevity is the soul of wit" (and sometimes, in Java,of readability).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic