簡體   English   中英

使用正則表達式查找字符串中的第一個單詞和最后幾個單詞

[英]Find the first word and last few words in a string using regex

使用這兩個regex表達式regPrefixregSuffix

final String POEM = "1. Twas brillig, and the slithy toves\n" + 
                    "2. Did gyre and gimble in the wabe.\n" +
                    "3. All mimsy were the borogoves,\n" + 
                    "4. And the mome raths outgrabe.\n\n";

String regPrefix = "(?m)^(\\S+)";   // for the first word in each line.
String regSuffix = "(?m)\\S+\\s+\\S+\\s+\\S+$";  // for the last 3 words in each line.
Matcher m1 = Pattern.compile(regPrefix).matcher(POEM);
Matcher m2 = Pattern.compile(regSuffix).matcher(POEM);

while (m1.find() && m2.find()) {
    System.out.println(m1.group() + " " + m2.group());
}

我得到正確的輸出為:

1. the slithy toves
2. in the wabe.
3. were the borogoves,
4. mome raths outgrabe.

是否可以將這兩個正則表達式合並為一個,並獲得相同的輸出? 我嘗試了類似的東西:

String singleRegex = "(?m)^(\\S+)\\S+\\s+\\S+\\s+\\S+$";

但這對我沒有用。

對兩個捕獲組使用單個模式:

String regex = "(?m)^(\\S+).*?((?:\\s+\\S+){3})$";
Matcher m = Pattern.compile(regex).matcher(POEM);
while (m.find()) {
    System.out.println(m.group(1) + m.group(2));
}

1. the slithy toves
2. in the wabe.
3. were the borogoves,
4. mome raths outgrabe.

演示版

暫無
暫無

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

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