Java 中的模式 MULTILINE 字段及其示例
javaobject oriented programmingprogramming更新于 2024/5/8 8:44:17
启用多行模式。
一般而言,^ 和 $ 元字符会将给定输入的开头和结尾与指定字符进行匹配,而不管其中有多少行。
示例 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
public static void main( String args[] ) {
//String regex = "(^This)";//.*t$)";
String input = "2234 This is a sample text\n"
+ "1424 This second 2335 line\n"
+ "This id third 455 line\n"
+ "Welcome to Tutorialspoint\n";
Pattern pattern = Pattern.compile("^([0-9]+).*");//, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
输出
2234
当您将其用作 compile() 方法的标志值时,整个输入序列将被视为一行,并且元字符 ^ 和 $ 与给定输入序列的开头和结尾匹配。
示例 2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
public static void main( String args[] ) {
//String regex = "(^This)";//.*t$)";
String input = "2234 This is a sample text\n"
+ "1424 This second 2335 line\n"
+ "This id third 455 line\n"
+ "Welcome to Tutorialspoint\n";
Pattern pattern = Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(input);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
输出
2234 1424
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

