您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,要实现非贪婪匹配,需要在量词后面添加一个问号(?)。量词包括:*
(0次或多次)、+
(1次或多次)、?
(0次或1次)以及{m,n}
(m到n次)。在量词后面添加问号会使匹配尽可能少的字符。
例如,假设我们有以下文本:
String text = "<tag>hello</tag><tag>world</tag>";
我们想要匹配<tag>
标签之间的内容。可以使用以下正则表达式:
String regex = "<tag>(.*?)</tag>";
这里的.*
表示匹配任意字符(.
)0次或多次(*
),而问号(?
)使其变为非贪婪匹配。这样,它将尽可能少地匹配字符,直到遇到第一个</tag>
。
以下是一个完整的Java示例:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String text = "<tag>hello</tag><tag>world</tag>";
String regex = "<tag>(.*?)</tag>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
输出结果:
hello
world
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。