Regular Expression

F

Fritz Bayer

Hello,

the following code snippet:

String replacementPattern = "-$1 $2-";
Pattern patter = Pattern.compile("http://(.*?)/(.*)");
pattern.matcher("http://www.example.com/test/index.html").replaceFirst(replacementPattern);
pattern.matcher("http://www.example.com/").replaceFirst(replacementPattern);
pattern.matcher("http:///").replaceFirst(replacementPattern);

will generate the following output:

-www.example.com /test/index.html-
-www.example.com -
- -

What I would like to achieve is to print out a constant infront of
each capturing group, if and only if, the group is not empty.

In other words: I'm looking for a value of "String
replacementPattern", which will generate the following output for the
GIVEN code above:

-host:www.example.com uri:/test/index.html-
-host:www.example.com -
--

I only know how to always print something infront of each capturing
group, regardless of whether or not it was empty ( String
replacementPattern = "- host:$1 uri:$2-";).

Fritz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top