Tie*_*yen 36 java regex string
我尝试在<%=和%>之间获取字符串,这是我的实现:
String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>");
String[] result = pattern.split(str);
System.out.println(Arrays.toString(result));
Run Code Online (Sandbox Code Playgroud)
它回来了
[ZZZZL , AFFF ]
Run Code Online (Sandbox Code Playgroud)
但我的期望是:
[ dsn , AFG ]
Run Code Online (Sandbox Code Playgroud)
我错在哪里以及如何纠正它?
jlo*_*rdo 64
你的模式很好.但你不应该把split()
它扔掉,你应该find()
这样做.以下代码给出了您要查找的输出:
String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Run Code Online (Sandbox Code Playgroud)
Pin*_*yni 25
我在这里回答了这个问题:https: //stackoverflow.com/a/38238785/1773972
基本上用
StringUtils.substringBetween(str, "<%=", "%>");
Run Code Online (Sandbox Code Playgroud)
这需要使用"Apache commons lang"库:https: //mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4
这个库有很多用于处理字符串的有用方法,你将真正受益于在java代码的其他方面探索这个库!
Jlordo 方法涵盖特定情况。如果您尝试从中构建抽象方法,您可能会面临检查“ textFrom
”是否在“ textTo
”之前的困难。否则,方法可以返回textFrom
文本中其他出现的“ ”的匹配项。
这是一个现成的抽象方法,它涵盖了这个缺点:
/**
* Get text between two strings. Passed limiting strings are not
* included into result.
*
* @param text Text to search in.
* @param textFrom Text to start cutting from (exclusive).
* @param textTo Text to stop cuutting at (exclusive).
*/
public static String getBetweenStrings(
String text,
String textFrom,
String textTo) {
String result = "";
// Cut the beginning of the text to not occasionally meet a
// 'textTo' value in it:
result =
text.substring(
text.indexOf(textFrom) + textFrom.length(),
text.length());
// Cut the excessive ending of the text:
result =
result.substring(
0,
result.indexOf(textTo));
return result;
}
Run Code Online (Sandbox Code Playgroud)
您的正则表达式看起来是正确的,但您splitting
使用它而不是matching
使用它。你想要这样的东西:
// Untested code
Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
94405 次 |
最近记录: |