gpt4 book ai didi

java - 正则表达式,试图匹配不超过一个句点?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:51 27 4
gpt4 key购买 nike

使用:http://www.regexplanet.com/advanced/java/index.html

并测试正则表达式:

\.{0,1} 

(?=.*?\.{0,1})

我指的是这个:http://www.rexegg.com/regex-lookarounds.html ,并尝试其他组合,但没有任何效果符合我的要求。

例如,对于测试输入和匹配,我期望..

lo.cat.tion - no match
location - match
loc_ation - match
loc.ation - match

但它告诉我根本没有匹配项。我在这里做错了什么? :(

最佳答案

一种在整个输入中只匹配一个点或不匹配点的简单方法如下:

String[] input = {
"lo.cat.tion", // - no match
"location", // - match
"loc_ation", // - match
"loc.ation" // - match
};
// | start of input
// || non dots, 0 or more
// || | 1 dot or nothing (dot requires \\escaping here)
// || | | non dots, 0 or more
// || | | | end of input
Pattern p = Pattern.compile("^[^.]*\\.?[^.]*$");
for (String s: input) {
Matcher m = p.matcher(s);
// we use "matches" instead of "find", to match the entire input here,
// although in this context both methods yield equivalent results
System.out.printf("Matches for \"%s\"? %b%n", s, m.matches());
}

输出

Matches for "lo.cat.tion"? false
Matches for "location"? true
Matches for "loc_ation"? true
Matches for "loc.ation"? true

关于java - 正则表达式,试图匹配不超过一个句点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25037393/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com