我有以下正则表达式
(?i)\b((https?:\/\/www\.)|(https?:\/\/)|(www\.))?(localhost).*\b
和以下网址
http://localhost:8081/saman/ab/cde/fgh/ijkl.jsf?gdi=ff8081abcdef02a011b0af032170001&ci=
同时使用 https://regex101.com/ 时它匹配和 http://rubular.com/r/kyiKS9OlsM
但当末尾有特殊字符时,url不匹配
import java.text.Format;
import java.text.MessageFormat;
import java.util.regex.Pattern;
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
private static final String URL_MATCH_REGEX = "(?i)\\b((https?:\\/\\/www\\.)|(https?:\\/\\/)|(www\\.))?({0}).*\\b";
private static final Format format = new MessageFormat(URL_MATCH_REGEX);
static String regex = "";
static String url = "http://localhost:8081/saman/ab/cde/fgh/ijkl.jsf?gdi=ff8081abcdef02a011b0af032170001&ci=";
public static void main(String[] args) {
try {
regex = format.format(new Object[]{replaceDomainToUseInRegex("localhost")});
System.out.println(regex);
Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher( url ).matches());
} catch (Exception e) {
}
}
private static String replaceDomainToUseInRegex(String domain) {
return domain.replace(".", "\\.").replace("/", "\\/").replace("?", "\\?");
}
}
谁能帮我解决这个问题?
最佳答案
您的问题是您使用了两种不同的匹配项。 Java 的 matches()
要求整个字符串与正则表达式相匹配。 regex101.com 没有。所以它表示如果输入字符串的任何子字符串 与正则表达式匹配,则匹配。但是,在 regex101.com 中,您可以通过将 ^
放在正则表达式的前面并将 $
放在末尾来获得相同类型的匹配;现在它需要整个字符串来匹配。而且不匹配。
(\b
匹配“单词边界”;它匹配非单词字符和单词字符(按任意顺序)之间或 word 字符和字符串的开头或结尾。=
不是单词字符,因此 \b
与 之间的位置不匹配=
和字符串的结尾。)
关于java - 在线工具上的正则表达式匹配在末尾有特殊字符时在 Java 中不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38733877/