在java中的两个字符串之间提取字符串
我尝试在之间获取字符串,这是我的实现:
String str = "ZZZZL AFFF "; Pattern pattern = Pattern.compile(""); String[] result = pattern.split(str); System.out.println(Arrays.toString(result));
它回来了
[ZZZZL , AFFF ]
但我的期望是:
[ dsn , AFG ]
我错在哪里以及如何纠正它?
你的模式很好。 但你不应该split()
它,你应该find()
它。 以下代码给出了您要查找的输出:
String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>"; Pattern pattern = Pattern.compile("<%=(.*?)%>"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.group(1)); }
我在这里回答了这个问题: https : //stackoverflow.com/a/38238785/1773972
基本上用
StringUtils.substringBetween(str, "<%=", "%>");
这需要使用“Apache commons lang”库: https : //mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4
这个库有很多用于处理字符串的有用方法,你将真正受益于在java代码的其他方面探索这个库!
你的正则表达式看起来是正确的,但你正在splitting
它而不是与之matching
。 你想要这样的东西:
// Untested code Matcher matcher = Pattern.compile("<%=(.*?)%>").matcher(str); while (matcher.find()) { System.out.println(matcher.group()); }
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; }
- 在ssl(ldaps)的支持下连接活动目录
- PropertyPlaceholderConfigurer和.properties文件中的环境变量
- 如何在Spring中将Multipart文件作为字符串读取?
- 在JAVA中使用Date类处理TimeZone更改
- 尝试将JPA与Derby一起使用时ClassNotFoundException:org.apache.derby.jdbc.EmbeddedDriver
- 在IntelliJ IDEA中为Tomcat设置了哪些应用程序上下文?
- 为什么在Object中定义了equals和hashCode?
- 如何将JavaScript函数传递给Java方法以充当回调(Rhino)
- 用java移动形状