簡體   English   中英

當最后有特殊字符時,在線工具上的正則表達式匹配在Java中不匹配

[英]Regular expression match on online tool does not match in Java when there is a special character at the end

我有以下正則表達式

(?i)\b((https?:\/\/www\.)|(https?:\/\/)|(www\.))?(localhost).*\b

並跟隨網址

HTTP://本地主機:8081 /三安/ 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匹配“單詞邊界”;它匹配非單詞字符和單詞字符(按任意順序)之間的“零寬度子字符串”,或單詞字符與字符串的開頭或結尾之間的“零寬度子字符串”。 =不是單詞字符,因此\\b=和字符串結尾之間的位置不匹配。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM