ViChU ViChU - 1 year ago 147
Java Question

Regex to get value between two colon excluding the colons

I have a string like this:


Now I want to take the POST alone from the string. I did this by using this regex


But this gives me a value along with colons. ie I get this:


but I need this


My code to match the same and replace it is as follows:

String ss = "something:POST:/some/path/";
Pattern pattern = Pattern.compile(":([a-zA-Z]+):");
Matcher matcher = pattern.matcher(ss);

if (matcher.find()) {
ss = ss.replaceFirst(":([a-zA-Z]+):", "*");


I've decided to use the lookahead/lookbehind regex since I did not want to use
with colons such as
. This is my final solution.

String s = "something:POST:/some/path/";
String regex = "(?<=:)[a-zA-Z]+(?=:)";

Matcher matcher = Pattern.compile(regex).matcher(s);

if (matcher.find()) {
s = s.replaceFirst(, "*");
System.out.println("replaced: " + s);
else {
System.out.println("not replaced: " + s);

Answer Source

There are two approaches:

  • Keep your Java code, and use lookahead/lookbehind (?<=:)[a-zA-Z]+(?=:), or
  • Change your Java code to replace the result with ":*:"

Note: You may want to define a String constant for your regex, since you use it in different calls.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download