aspose file tools*
The moose likes Beginning Java and the fly likes java regex help needed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java regex help needed" Watch "java regex help needed" New topic
Author

java regex help needed

saud rahman
Greenhorn

Joined: Oct 20, 2009
Posts: 1
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

Joined: Sep 26, 2009
Posts: 188
Look for quantifier '?' how they are used
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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
 
subject: java regex help needed