简体   繁体   中英

I dont know how can use this regex in java

I have the next regex, that works when I test online in: http://www.regexr.com/ but not works on my java project:

(?:function jo|[{;]jo\s*=\s*function)\((.*?[a-z,]+)\){(.*?[^}]+)}

My code:

Pattern p2 = Pattern.compile("(?:function "+funcname+"|[{;]"+funcname+"\\s*=\\s*function)\\((.*?[a-z,]+)\\){(.*?[^}]+)}");

My error:

07-23 23:43:17.608: E/AndroidRuntime(1724): (?:function jo|[{;]jo\s*=\s*function)\((.*?[a-z,]+)\){(.*?[^}]+)}
07-23 23:43:17.608: E/AndroidRuntime(1724):                                                        ^

My example test string:

{return a.reverse()}};function jo(a){a=a.split("");a=io.aS(a,53);a=io.Y7(a,19);a=io.aS(a,9);a=io.km(a,2);a=io.Y7(a,29);a=io.km(a,1);return a.join("")};function ko(){};var lo

I want extract this part:

a=a.split("");a=io.aS(a,53);a=io.Y7(a,19);a=io.aS(a,9);a=io.km(a,2);a=io.Y7(a,29);a=io.km(a,1);return a.join("")

Thanks a lot, I am coming crazy with regex.

I just want to say that using regex to parse code is not best idea. You should search for parser and use it instead.

It seems that you forgot to escape { and } at the end of your regex. You need to escape them since they are regex metacharacters used to specify how many times something can appear like

  • a{4} - means that a must appear exactly 4 times
  • a{2,4} - means that a must appear 2, 3 or 4 times
  • a{2,} - means that a must appear 2 or more times.

Try with

Pattern p2 = Pattern.compile("(?:function " + funcname + "|[{;]"
        + funcname + "\\s*=\\s*function)\\((.*?[a-z,]+)\\)\\{(.*?[^}]+)\\}");
// parts changed                                          ^^^          ^^^

Demo:

String text = "{return a.reverse()}};function jo(a){a=a.split(\"\");a=io.aS(a,53);a=io.Y7(a,19);a=io.aS(a,9);a=io.km(a,2);a=io.Y7(a,29);a=io.km(a,1);return a.join(\"\")};function ko(){};var lo";

String funcname = Pattern.quote("jo");// lets excape potential regex
                                      // special characters

Pattern p2 = Pattern.compile("(?:function " + funcname + "|[{;]"
        + funcname + "\\s*=\\s*function)\\((.*?[a-z,]+)\\)\\{(.*?[^}]+)\\}");

Matcher m = p2.matcher(text);
while (m.find())
    System.out.println(m.group(2));

Output:

a=a.split("");a=io.aS(a,53);a=io.Y7(a,19);a=io.aS(a,9);a=io.km(a,2);a=io.Y7(a,29);a=io.km(a,1);return a.join("")

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