简体   繁体   中英

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)

into

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

string[1] = AND

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.

Pattern pattern = 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.

这应该有效

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

应该管用。

这应该适合你。

\)::|::\(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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