簡體   English   中英

Java Regex:僅在單詞開頭找到匹配項

[英]Java Regex: find a match only at the beginnings of words

例如,我有一組字符串:

"Abc zcf",
"Abcd zcf",
"Zcf Abc",
"Zcf Abcd",
"Test ez",
"Rabc Jabc"

如何在這組字符串中找到任何單詞以“ abc”字符開頭的單詞? 在我的示例中,它將是字符串

"Abc zcf",
"Zcf Abc",
"Abcd zcf",
"Zcf Abcd"

您必須使用Pattern

final Pattern p = Pattern.compile("\\bAbc");

// ...

if (p.matcher(input).find())
    // match

僅供參考, \\b是“錨點”一詞。 Java對單詞字符的定義是下划線,數字或字母。

您需要匹配任何內容,然后匹配單詞邊界,然后匹配abc 您還希望以不區分大小寫的方式執行此操作。 模式

(?i).*\\babc.*

將工作。 一個簡單的例子

public static void main(String[] args) throws Exception {
    final Pattern pattern = Pattern.compile("(?i).*\\babc.*");

    final String[] in = {
        "Abc zcf",
        "Abcd zcf",
        "Zcf Abc",
        "Zcf Abcd",
        "Test ez",
        "Rabc Jabc"};

    for (final String s : in) {
        final Matcher m = pattern.matcher(s);
        if (m.matches()) {
            System.out.println(s);
        }
    }
}

輸出:

Abc zcf
Abcd zcf
Zcf Abc
Zcf Abcd

編輯

除了@fge關於匹配整個模式的評論之外,這里還有一種更巧妙的方法在String中搜索模式。

public static void main(String[] args) throws Exception {
    final Pattern pattern = Pattern.compile("(?i)(?<=\\b)abc");

    final String[] in = {
        "Abc zcf",
        "Abcd zcf",
        "Zcf Abc",
        "Zcf Abcd",
        "Test ez",
        "Rabc Jabc"};

    for (final String s : in) {
        final Matcher m = pattern.matcher(s);
        if (m.find()) {
            System.out.println(s);
        }
    }
}

這是說找abc 由之前 \\b -即字的邊界。 輸出是相同的。

您可以使用:

if( maChaine.startWith("Abc") ) 
{ 

    list.add( maChaine ) ; 
}

嘗試此正則表達式解決您的問題:

(^Abc| Abc)

暫無
暫無

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

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