[英]how to extract specific part of a string in java
考虑一下jsp文件中的该语句(jsp文件中还有更多类似的语句。)
<h:dataGrid something styleclass="styleclass1" something1
onClick="event" something2
<% this is a scriplet tag %>
something3
style="style1">
<h:output text>hello i am text</h:output text>
</h:dataGrid>
我想要的是从“ <”到“>”中提取(并将其存储在某处),其中:
< - is the one in "<h:dataGrid"
> - is the one in "style1>" and not the('>') one that appears in the end
of "</h:dataGrid>" or "<h:output text>" or "</h:output text>"
问题是文本b / w &&在多行中... &&在它们之间有scriplet标记..所以我不知道如何提取这个特定的字符串..我尝试使用一些正则表达式但是不能找不到确切的..
(这只是一个示例&&而不是此“”标记,它可能在这一行中再次类似于:
<h:output text>hello i am text</h:output text>
我想从“ <”到“>”中提取字符串,其中:
< - is the one in starting of "<h:output text>"
> - is the one in ending of "<h:output text>" and not the one in "</h:output text>"
但是,此示例与上述示例的不同之处在于,该示例不是多行的,并且不包含任何scriplet标签)
有人可以帮我这个忙吗?。任何特定的方法或正则表达式?
您可以尝试使用正则表达式,但是您可能需要编写一种方法,通过跟踪出现多少打开标签和关闭标签来为您排序...但是对于正则表达式:<(。*?)> <---这将进行搜索对于<和>之间的所有内容,请注意:如上例所示,空格由<+ space分隔。 您还必须转义字符。
按字符读取字符char。 当您到达开头时<
启动一个计数器,并开始将字符添加到StringBuilder
。 当您按下更多<
s时,您的计数器就会增加,而任何>
减少。 如果计数器达到0,则退出循环并返回StringBuilder.toString()。
您可以使用正则表达式,但是您使用的任何正则表达式的基础必须是具有不愿意的量词,例如.*?
,它不会消耗超过第一个匹配项,而贪婪的量词(例如.*
会消耗。
这里是单线:
String target = jsp.replaceAll("(?s)^.*?(<.*?[^%]>).*", "$1");
这将匹配第一个“ <”和第一个“>”之间(包括第一个“ <”和第一个“>”)的所有内容,并在其之前加上“%”,并将其提取(通过删除其余部分)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.