在 Java 中使用带有示例的 Pattern UNIX_LINES 字段
此标志启用 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" + "This is the second line\r" + "This is the third line\r"; //Regular expression to accept date in MM-DD-YYY format String regex = "^T.*e"; //Creating a Pattern object Pattern pattern = Pattern.compile(regex, Pattern.UNIX_LINES); //Creating a Matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; System.out.println(matcher.group()); } System.out.println("Number of matches: "+count); } }
输出
This is the first line This is the second line This is the third line Number of matches: 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" + "This is the second line\r" + "This is the third line\r"; //Regular expression to accept date in MM-DD-YYY format String regex = "^T.*e"; //Creating a Pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; System.out.println(matcher.group()); } System.out.println("Number of matches: "+count); } }
输出
This is the first line Number of matches: 1
广告