[英]Find words with 3 letters in Java
我想在每個元素中找到所有帶有3個字母的單詞。
在這篇文章中,我找到了正確的正則表達式,但是知道我正在嘗試使其在Java中運行。
Set<String> input = new HashSet<String>();
input.add("cat 123");
input.add("monkey");
input.add("dog");
Pattern p = Pattern.compile("\b[a-zA-Z]{3}\b");
for (String s : input) {
if (p.matcher(s).matches()) {
System.out.println(s);
}
}
在我來說,我想cat
與dog
被放出來了,但我只得到一個空的輸出。
您必須轉義反斜杠,即\\\\b
而不是\\b
:
Pattern p = Pattern.compile("\\\\b[a-zA-Z]{3}\\\\b");
創建一個匹配器,並使用“ find
和group
查找並顯示下一個匹配的分組:
for (String s : input) { Matcher m = p.matcher(s); while (m.find()) { System.out.println(m.group()); } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.