[英]Silly RegEx issue. What am I doing wrong?
String url = "hello world";
String p = "world";
Pattern pattern = Pattern.compile(p);
Matcher matcher = pattern.matcher(url);
if (matcher.matches()) {
int start = matcher.start();
int end = matcher.end();
}
我究竟做錯了什么? if語句永不被擊中怎么辦?
matches()
方法嘗試將整個字符串與模式匹配。 您需要find()
方法。
嘗試Matcher.find() 。 Matcher.matches()
檢查整個字符串是否與模式匹配。
您需要使用find
因為,
matchs嘗試將整型與整個字符串進行匹配,並在模式的開頭隱式地添加一個^並在該模式的末尾隱式添加$。
因此,您的模式相當於“ ^ world $”。
嘗試將模式更改為".*world.*"
:
String p = ".*world.*";
這樣,它將匹配包含“ world”的任何字符串。
我遇到了同樣的問題。 我不知道原因 如果有人知道問題,請在此處發布。 我已經解決了重復使用find()而不是match()的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.