ViChU ViChU - 2 months ago 35
Java Question

Regex to get value between two colon excluding the colons

I have a string like this:

something:POST:/some/path


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

:([a-zA-Z]+):


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

:POST:


but I need this

POST


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()) {
System.out.println(matcher.group());
ss = ss.replaceFirst(":([a-zA-Z]+):", "*");
}
System.out.println(ss);


EDIT:

I've decided to use the lookahead/lookbehind regex since I did not want to use
replace
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(matcher.group(), "*");
System.out.println("replaced: " + s);
}
else {
System.out.println("not replaced: " + s);
}

Answer

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.

Comments