java 如何使用正则匹配有class类名的a标签,并且在匹配到的a标签里面插入href
时间: 2023-02-26 20:53:17 浏览: 92
下面是一个使用Java正则表达式匹配带有class类名的a标签并在其中插入href的代码示例:
```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExExample {
public static void main(String[] args) {
String html = "<a class=\"example\" href=\"https://www.example.com\"></a>";
String className = "example";
String newHref = "https://www.newexample.com";
// 匹配带有class类名的a标签
Pattern pattern = Pattern.compile("<a class=\".*?" + className + ".*?\" href=\".*?\"></a>");
Matcher matcher = pattern.matcher(html);
// 如果匹配成功
if (matcher.find()) {
// 替换原来的href
html = html.replaceAll("href=\".*?\"", "href=\"" + newHref + "\"");
}
System.out.println(html);
}
}
```
输出结果:
```
<a class="example" href="https://www.newexample.com"></a>
```
在上面的代码中,我们首先使用`Pattern`类定义了一个正则表达式,该表达式用于匹配带有给定class类名的a标签。然后,我们使用`Matcher`类对原始HTML字符串进行了匹配,如果匹配成功,则使用`replaceAll`方法将原始HTML字符串中的href替换为新的href。