This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
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

java regex help needed

 
saud rahman
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I can have lines like these which I need to parse and retrieve values from:

'Name=ABC Occupation=SSS Age=23'

'Name=BBB Occupation=TTT'

'Name=BBB Occupation=TTT Age=34' etc. The age field is optional and times it won't be present.



This is my java code:

String regex = "Name=([A-Z]*)\\sOccupation=([A-Z]*)\\sAge=([0-9]*)"

Matcher matcher = Pattern.compile(reHeaderFormat).matcher(line);
if (matcher.find()) {

String name = matcher.group(1);

String occupation = matcher.group(2);

int age = Integer.parseInt(matcher.group(3));

} else{

//not matching

}

I need to change the regex expression to make the Age field optional, That is, if age field is present retrieve the value, else ignore. With my current expression only those lines with Age field are matching. Please help.



Thanks,

Saud
 
Rahul P Kumar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look for quantifier '?' how they are used
 
Campbell Ritchie
Sheriff
Posts: 48445
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

How about counting = symbols with a linear search through the string?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic