Use RegEx in Java to extract parameters in between parentheses

Posted by lars_bx on Stack Overflow See other posts from Stack Overflow or by lars_bx
Published on 2012-10-04T19:51:22Z Indexed on 2012/10/05 3:37 UTC
Read the original article Hit count: 789

Filed under:
|
|

I'm writing a utility to extract the names of header files from JSPs. I have no problem reading the JSPs line by line and finding the lines I need. I am having a problem extracting the specific text needed using regex. After looking at many similar questions I'm hitting a brick wall.

An example of the String I'll be matching from within is:

<jsp:include page="<%=Pages.getString(\"MY_HEADER\")%>" flush="true"></jsp:include>

All I need is MY_HEADER for this example. Any time I have this tag:

<%=Pages.getString

I need what comes between this:

<%=Pages.getString(\"  and this: )%>

Here is what I have currently (which is not working, I might add) :

String currentLine;
while ((currentLine = fileReader.readLine()) != null)
{
Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\]*)"); 
Matcher matcher = pattern.matcher(currentLine); 
while(matcher.find()) {
System.out.println(matcher.group(1).toString());                           
}}

I need to be able to use the Java RegEx API and regex to extract those header names.

Any help on this issue is greatly appreciated. Thanks!

EDIT:

Resolved this issue, thankfully. The tricky part was, after being given the right regex, it had to be taken into account that the String I was feeding to the regex was always going to have two " / " characters ( (/"MY_HEADER"/) ) that needed to be escaped in the pattern.

Here is what worked (thanks to the help ;-)):

Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\\"]*)"); 

© Stack Overflow or respective owner

Related posts about java

Related posts about regex