• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

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: 80754
486
  • 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?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic