简体   繁体   English

正则表达式与 - ,::,(和)

[英]Regex with -, ::, ( and )

I need to split the string 我需要拆分字符串

(age-is-25::OR::last_name-is-qa6)::AND::(age-is-20::OR::first_name-contains-test) (年龄为25 ::或::姓氏,是-QA6):: AND::(年龄为20 ::或:: FIRST_NAME,包含测试)

into

string[0] = (age-is-25::OR::last_name-is-qa6) string [0] =(age-is-25 :: OR :: last_name-is-qa6)

string[1] = AND string [1] = AND

string[2] = (age-is-20::OR::first_name-contains-test) string [2] =(age-is-20 :: OR :: first_name-contains-test)

I tried writing so many regex expressions, but nothing works as expected. 我尝试编写这么多正则表达式,但没有任何方法可以正常工作。

Using the following regex, Matcher.groupCount() which returns 2 but assigning results to an arraylist returns null as the elements. 使用以下正则表达式,Matcher.groupCount()返回2但将结果赋给arraylist返回null作为元素。

Pattern pattern = Pattern.compile("(\\\\)::)?|(::\\\\()?"); 模式模式= Pattern.compile(“(\\\\)::)?|(:: \\\\()?”);

I tried to split it using ):: or ::(. 我尝试使用)::或:: :(拆分它。

I know the regex looks too stupid, but being a beginner this is the best I could write. 我知道正则表达式看起来太愚蠢,但作为初学者,这是我能写的最好的。

You can use positive lookahead and lookbehind to match the first and last parentheses. 您可以使用正向前瞻和后瞻来匹配第一个和最后一个括号。

String str = "(age-is-25::OR::last_name-is-qa6)::AND::(age-is-20::OR::first_name-contains-test)";

for (String s : str.split("(?<=\\))::|::(?=\\()"))
    System.out.println(s);

Outputs: 输出:

(age-is-25::OR::last_name-is-qa6)
AND
(age-is-20::OR::first_name-contains-test)

Just a note however: It seems like you are parsing some kind of recursive language. 但是请注意:看起来你正在解析某种递归语言。 Regular expressions are not good at doing this. 正则表达式不擅长这样做。 If you are doing advanced parsing I would recommend you to look at other parsing methods. 如果您正在进行高级解析,我建议您查看其他解析方法。

To me it looks like a big part of your stress comes from the need for escaping special characters in your search term. 对我来说,你的压力很大一部分来自于在你的搜索词中逃避特殊字符的需要。 I highly recommend to not do manual escaping of special characters, but instead to use Pattern.quote(...) for the escaping. 我强烈建议不要手动转义特殊字符,而是使用Pattern.quote(...)进行转义。

这应该有效

 "(?<=\\))::|::(?=\\()"
textString.split("\\)::|::\\(") 

应该管用。

这应该适合你。

\)::|::\(

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

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