Java 中的模式 UNIX_LINES 字段及其示例

javaobject oriented programmingprogramming更新于 2024/5/8 9:48:17

此标志启用 Unix 行模式。在 Unix 行模式下,仅使用 '\n' 作为行终止符,而 ‘\r’ 则被视为文字字符。

示例 1 

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
   public static void main(String[] args) {
      String input = "This is the first line\r"
         + "这是第二行\r"
         + "这是第三行\r";
      //正则表达式接受 MM-DD-YYY 格式的日期
      String regex = "^T.*e";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex, Pattern.UNIX_LINES);
      //创建一个 Matcher 对象
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
         System.out.println(matcher.group());
      }
      System.out.println("匹配数:"+count);
   }
}

输出

这是第一行
这是第二行
这是第三行
匹配数:1

而在正常模式下 \r 被视为回车符。

示例 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LTERAL_Example {
   public static void main(String[] args) {
      String input = "This is the first line\r"
         + "这是第二行\r"
         + "这是第三行\r";
      //正则表达式接受 MM-DD-YYY 格式的日期
      String regex = "^T.*e";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个 Matcher 对象
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
         System.out.println(matcher.group());
      }
      System.out.println("匹配数:"+count);
   }
}

输出

这是第一行
匹配数:1

相关文章


有用资源