簡體   English   中英

Java正則表達式通過變量輸入和字符串輸入給出不同的結果

[英]Java Regular Expression giving a different result with variable input and string input

我正在嘗試將啟用通配符的url轉換為正則表達式( Pattern ),以便稍后可以使用它與通配符的url匹配。

然后我發現,盡管具有相同的字符串值,但使用變量輸入( String regex = 'str' )與直接字符串輸入"regex str"會產生不同的結果。

我在官方文件中找不到這種行為。

String destination = "*.example.com";
String regex = destination.replaceAll("\\.", "\\\\\\\\.");
regex = regex.replaceAll("\\*", "\\.\\*");
System.out.println(regex);                             //this gives ".*\\.example\\.com"

System.out.println(Pattern.matches(regex, "office.example.com"));         //false
System.out.println(Pattern.matches(".*\\.example\\.com", "office.example.com"));  //true

我們需要兩個'\\',因為它在字符串變量定義中。 語句regex =“。* \\\\。example \\\\。com”,執行該語句后,regex的實際值為“。* \\。example \\ .com”。 因此,您可以更改為destination.replaceAll(“ \\\\。”,“ \\\\\\\\。”)以使其起作用。

這里有兩種轉義:字符串和正則表達式。 很容易忘記什么是什么。 使用replaceAll使事情變得更加困難。

我想你要:

String destination = "*.example.com";
String regex = destination.replace(".", "\\.").replace("*", ".*");

System.out.println(Pattern.matches(regex, "office.example.com"));
System.out.println(Pattern.matches(".*\\.example\\.com", "office.example.com"));

暫無
暫無

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

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