File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java regex help needed" Watch "java regex help needed" New topic

java regex help needed

saud rahman

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 =;

String occupation =;

int age = Integer.parseInt(;

} 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.


Rahul P Kumar
Ranch Hand

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

Joined: Oct 13, 2005
Posts: 45292
Welcome to JavaRanch

How about counting = symbols with a linear search through the string?
I agree. Here's the link:
subject: java regex help needed
It's not a secret anymore!