简体   繁体   English

使用包含括号'(''的正则表达式从字符串中提取子字符串

[英]Extract a substring from a string using regex that includes a 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 enclosed and if I try and escape it then complains that its not a valid escaped character. 我试图弄清楚如何从字符串中提取子字符串,但字符串包含一个括号,Java然后抱怨它没有被封闭,如果我尝试逃避它,然后抱怨它不是一个有效的转义字符。

I have the following string: 我有以下字符串:

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

I'm 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 currently 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 the ( between ] and /monitors but when I do Android Studio then says unclosed group . If I try and escape the slash \\( it then says illegal escape character. 有了上面的内容,我没有(之间)和/监视器,但是当我做Android Studio然后说unclosed group 。如果我试图逃避斜线\\(它然后说非法转义字符。

What I am expecting to get back is 2972550 . 我期待回来的是2972550

You missed some chars on the way to the digits and failed to escape the ( , ) and [ , use 你在前往数字的路上错过了一些字符而无法逃避()[ ,使用

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);
}

Here is a regex demo and an online Java demo . 这是一个正则表达式演示和一个在线Java演示

Details 细节

  • \\[ - a [ \\[ - 一个[
  • Monitor Status - a literal substring Monitor Status - 文字子字符串
  • ] - a literal ] ] - 字面意思]
  • \\( - a literal ( \\( - 文字(
  • / - a / / - 一个/
  • monitors# - a literal substring monitors# - 文字子串
  • (\\d+) - Group 1: one or more digits. (\\d+) - 第1组:一个或多个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM