Extract a substring from a string using a regular expression that contains the bracket '('

I am trying to figure out how to extract a substring from a string, but the string contains a bracket, and Java then complains that it is not nested, and if I try to avoid it, it complains that its invalid escaped character.

I have the following line:

[Monitor Status](/monitors#2972550?)] · [[Edit Monitor](/monitors#2972550/edit)] · [[Related Logs](/logs?query=)]
%%%

I am trying to extract the number after / monitors #. The number is in two places and will always be the same in both places, so I'm just trying to extract the first number.

Below is what I have:

Pattern pattern = Pattern.compile("[Monitor Status]/monitors#(\\d+)");                   
Matcher matcher = pattern.matcher(monitorDetails);
if (matcher.find())
{
     String monitor_id = matcher.group(1);
     monitorDetailsContainer.setVisibility(View.VISIBLE);
}

With the above, I don’t have (between] and / monitors, but when I do Android Studio, it says unclosed group. If I try to escape from the slash \(, then an illegal evacuation symbol will be indicated.

, , 2972550.

+4
1

(, ) [,

Pattern pattern = Pattern.compile("\\[Monitor Status]\\(/monitors#(\\d+)");                   
Matcher matcher = pattern.matcher(monitorDetails);
if (matcher.find())
{
     String monitor_id = matcher.group(1);
     monitorDetailsContainer.setVisibility(View.VISIBLE);
}

regex demo - Java.

  • \[ - a [
  • Monitor Status -
  • ] - ]
  • \( - (
  • / - a /
  • monitors# -
  • (\d+) - 1: .
+3

Source: https://habr.com/ru/post/1694146/


All Articles