[英]Regex in Java get part of string
I'm having trouble with regex in Java. 我在Java中遇到了正则表达式问题。 I'm trying to capture the central part of a string between two parts:
我正在尝试捕获两个部分之间的字符串的中心部分:
function gH(a){a=a.split("");
and 和
return a.join("")};
The problem is that the center of the string changes all the time. 问题在于字符串的中心始终在变化。 And the name of function, too.
还有函数的名称。
Here is an example: 这是一个例子:
;function gH(a){a=a.split("");fH.vF(a,36);fH.DZ(a,42);fH.kG(a,1);fH.vF(a,23);fH.DZ(a,29);fH.vF(a,41);fH.DZ(a,2);fH.kG(a,2);fH.vF(a,17);return a.join("")};
The part I want is: 我想要的部分是:
fH.vF(a,36);fH.DZ(a,42);fH.kG(a,1);fH.vF(a,23);fH.DZ(a,29);fH.vF(a,41);fH.DZ(a,2);fH.kG(a,2);fH.vF(a,17);
Here is my code: 这是我的代码:
pattern = ";function ..\\(a\\){a=a\\.split\\(\"\"\\);(.*?);return a\\.join\\(\"\"\\)};";//;return a\\.join\\(\"\"\\)\\};";
r = Pattern.compile(pattern);
m = r.matcher(response);
String code = "";
while(m.find())
{
shift = m.group(1);
}
System.out.println("Center:" + code);
This code doesn't return what I want. 这段代码没有返回我想要的。
Here you are, fixed a couple of issues, and now it is working (see sample program here ): 在这里,您已经解决了几个问题,现在可以正常工作了(请参见此处的示例程序 ):
String response = ";function gH(a){a=a.split(\"\");fH.vF(a,36);fH.DZ(a,42);fH.kG(a,1);fH.vF(a,23);fH.DZ(a,29);fH.vF(a,41);fH.DZ(a,2);fH.kG(a,2);fH.vF(a,17);return a.join(\"\")};";
String pattern = "function\\s+..\\(a\\)\\{a=a\\.split\\(\"\"\\);(.*?)return\\s+a\\.join\\(\"\"\\)};";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(response);
String code = "";
while(m.find())
{
code = m.group(1);
}
System.out.println("Center:" + code);
Output: 输出:
Center:fH.vF(a,36);fH.DZ(a,42);fH.kG(a,1);fH.vF(a,23);fH.DZ(a,29);fH.vF(a,41);fH.DZ(a,2);fH.kG(a,2);fH.vF(a,17);
code
is now correcly assigned the value of the first capturing group, and used later. 现在,已为
code
分配了第一个捕获组的值,并在以后使用。 I also prefer \\s
over literal spaces as it is more convenient to debug regexes later. 我也更喜欢
\\s
不是文字空间,因为以后调试正则表达式更方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.