简体   繁体   English

正则表达式无法按预期工作-JAVA

[英]Regular expression not working as expected - JAVA

I am using the following regex "location in \\\\((.*?)\\\\)" 我正在使用以下正则表达式"location in \\\\((.*?)\\\\)"

against the following string: pro 300\\nlocation in ("aaa","bbb") 针对以下字符串: pro 300 \\ nlocation在(“ aaa”,“ bbb”)中

according to online regex test for java, the result should be "aaa","bbb" but when I run that in java code like this: 根据针对Java的在线正则表达式测试,结果应为“ aaa”,“ bbb”,但是当我在Java代码中运行如下代码时:

conditions.replaceAll("location in \\((.*?)\\)", "$1");

I get pro 300"aaa","bbb" 我得到专业版300“ aaa”,“ bbb”

What I am doing wrong? 我做错了什么? Thanks in advance. 提前致谢。

replaceAll() is replacing the part of conditions matched by group(0) of your regex. replaceAll()替换由正则表达式的group(0)匹配的部分conditions

To retrieve only the part inside (...) you need to use: 要仅检索(...)内部的部分,您需要使用:

Pattern p = Pattern.compile("location in \\((.*?)\\)");
Matcher m = p.matcher(conditions);
if (m.find())
{
    String s = m.group(1);
}

This will retrieve the inner bracket of your regular expression (.*?) 这将检索正则表达式(.*?)的内括号

Additionally to Rossiar's answer, if you don't want to use Pattern and Matcher classes and just want to use replaceAll method then your code is working as expected , you have below string: 除了Rossiar的答案外,如果您不想使用PatternMatcher类,而只想使用replaceAll方法,那么您的代码将按预期工作 ,您可以使用以下字符串:

pro 300\nlocation in ("aaa","bbb")
         ^^^^^^^^^^^^^^^^^^^^^^^^^ and you replace this by "aaa","bbb"

So, your final string is: 因此,您的最终字符串是:

pro 300\n"aaa","bbb"

String.replaceAll String.replaceAll

If you want just to get "aaa","bbb" using replaceAll , you will have to match the complete string by using: 如果您只想使用replaceAll获得"aaa","bbb" ,则必须使用以下方法来匹配完整的字符串:

conditions = conditions.replaceAll(".*location in \\((.*?)\\).*", "$1");
                                    ^--------- Note ---------^

Or for your specific string you could use: 或者对于您的特定字符串,您可以使用:

"pro 300\nlocation in (\"aaa\",\"bbb\")".replaceAll(".*\\((.*?)\\).*", "$1");

I can't test it right now if \\n is not being matched by .* , so in case it isn't then you can replace multilines by using single line flag or doing a regex trick: 如果\\n.*不匹配,我现在无法对其进行测试,因此如果不匹配,则可以使用single line标志或执行正则表达式技巧来替换多single line

Single line flag 单行标志

"pro 300\nlocation in (\"aaa\",\"bbb\")".replaceAll("(?s).*\\((.*?)\\).*", "$1");

Working demo 工作演示

Regex trick 正则表达式的把戏

"pro 300\nlocation in (\"aaa\",\"bbb\")".replaceAll("[\\s\\S]*\\((.*?)\\)[\\s\\S]*", "$1");

Working demo 工作演示

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

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