Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

java regex help needed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look for quantifier '?' how they are used
 
Marshal
Posts: 79632
380
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Welcome to JavaRanch

How about counting = symbols with a linear search through the string?
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic