溫馨提示×

java正則如何處理多行文本

小樊
124
2024-11-15 08:41:47
欄目: 編程語言

在Java中,處理多行文本的正則表達式需要使用(?s)標志。這個標志會讓.字符匹配任何字符,包括換行符。下面是一個簡單的例子,展示了如何使用正則表達式處理多行文本:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MultiLineRegexExample {
    public static void main(String[] args) {
        String text = "This is the first line.\nThis is the second line.\nThis is the third line.";

        // 使用(?s)標志讓.匹配任何字符,包括換行符
        String regex = "(?s)line";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {
            System.out.println("Found: " + matcher.group());
        }
    }
}

在這個例子中,我們使用了正則表達式"line"來查找文本中的所有"line"(不區分大小寫)。(?s)標志確保了.字符可以匹配換行符。運行這個程序,你將看到以下輸出:

Found: This is the first line.
Found: This is the second line.
Found: This is the third line.

這表明正則表達式成功地匹配了多行文本中的每一行。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女