java中使用通配符的正则表达式
有没有办法使用带有通配符的正则表达式?具体来说,我有一个字符串短语和另一个字符串目标。我想使用 match 方法在目标之前和之后的字符不是 az 的短语中找到目标的第一次出现。
更新:
有没有办法使用带有以下正则表达式的字符串方法matches():
"(?<![a-z])" + "hello" + "(?![a-z])";
回答
您可以使用正则表达式, "(?<![a-z])" + Pattern.quote(phrase) + "(?![a-z])"
在regex101 上使用短语 = "hello" 进行演示。
(?<![a-z]): 负向后视[a-z](?![a-z]): 负前瞻[a-z]
Java演示:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Test
String phrase = "hello";
String regex = "(?<![a-z])" + Pattern.quote(phrase) + "(?![a-z])";
Pattern pattern = Pattern.compile(regex);
Stream.of(
"hi hello world",
"hihelloworld"
).forEach(s -> {
Matcher matcher = pattern.matcher(s);
System.out.print(s + " => ");
if(matcher.find()) {
System.out.println("Match found");
}else {
System.out.println("No match found");
}
});
}
}
输出:
hi hello world => Match found
hihelloworld => No match found
hi hello world => Match found
hihelloworld => No match found
如果您想要完全匹配,请使用正则表达式,.*(?<![a-z]) + Pattern.quote(phrase) +(?![a-z]).*如regex101.com 所示。模式,.*表示任意次数的任意字符。其余的模式已经在上面解释过了。.*匹配前后的存在将确保覆盖整个字符串。
Java演示:
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
// Test
String phrase = "hello";
String regex = ".*(?<![a-z])" + Pattern.quote(phrase) + "(?![a-z]).*";
Stream.of(
"hi hello world",
"hihelloworld"
).forEach(s -> System.out.println(s + " => " + (s.matches(regex) ? "Match found" : "No match found")));
}
}
输出:
- It might be safer to escape the dynamic part. `"(?<![a-z])" + Pattern.quote(phrase) + "(?![a-z])"`