简体   繁体   English

正则表达式使用结果替换字符串

[英]Regex using result for replace String

I want select all the text between <h3> 我想选择<h3>之间的所有文本<h3> and /h3> < /h3> < /h3> < . After selection I like to replace the value of my String with the result. 选择之后,我想用结果替换String的值。 In the following example the result should be Basic Information 在以下示例中,结果应为“ 基本信息”

String test="<h3>Basic Information</h3> <div>";
test = test.replaceAll("<h3>(.*?)</h3>", "$1");

But at the moment the result is 但是目前的结果是

Basic Information <div> 基本信息< div>

With regex you can do: 使用正则表达式,您可以执行以下操作:

String test="<h3>Basic Information</h3> <div>";
String repl = test.replaceFirst(".*<h3>([^&]+).*/h3> <.*", "$1");
//=> Basic Information

Though you can avoid regex altogether and use String APIs to extract same text as well. 虽然您可以完全避免使用正则表达式,也可以使用String API提取相同的文本。

Alternatively you can use this regex for matching: 另外,您可以使用此正则表达式进行匹配:

<h3>([^&]+).*/h3> <

and grab captured group #1 using Pattern and Matches APIs. 并使用Pattern and Matches API获取捕获的#1组。

Try this: 尝试这个:

Pattern pattern = Pattern.compile("<h3>(.*)<\\/h3>");
Matcher matcher = pattern.matcher("<h3>Basic Information</h3> <div>");
matcher.find();
StringBuffer sb = new StringBuffer();
matcher.appendReplacement(sb,"$1");
String result = sb.toString();

The reason why you cannot do that with just replaceFirst it's because the appendTail method is called at the end of the replaceFirst method. 你之所以不能这样做,只有replaceFirst那是因为appendTail方法被调用在结束replaceFirst方法。 The matcher will replace the groups you did not specified with empty ,the groups you did specified with their value and of course the non-matching bits which well, since no match was created for them, they do not get replaced at all. 匹配器会将您未指定的组替换为 ,将您指定的组替换为它们的 ,当然还有不匹配的位,这些位很好,因为没有为它们创建匹配项,所以它们根本不会被替换。

In the case of your query: 对于您的查询:

group 0 : <h3> 组0 :<h3>

group 1 : Basic Information 第一组 :基本信息

group 0 : </h3> 组0 :</ h3>

non-match : <div> 不匹配 :<div>

This is just a generic example of what you can do with the matchers. 这只是您可以使用匹配器的一般示例。 Of course if you just want the group in specific... Well just use: 当然,如果您只想要特定的组...那么请使用:

matcher.group(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM