File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java regex help needed

 
saud rahman
Greenhorn
Posts: 1
  • 0
  • 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
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look for quantifier '?' how they are used
 
Campbell Ritchie
Sheriff
Pie
Posts: 47292
52
  • 0
  • 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?
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic