例:
匹配输入串A: 1001000100
贪婪匹配:
使用 1.*1 将会匹配到10010001
非贪婪匹配:
使用 1.*?1 将会匹配到1001
主要区别在于是否加?当?紧随任何其他限定符之后时,匹配模式是"非贪心的"。“非贪心的"模式匹配搜索到的、尽可能短的字符串,而默认的"贪心的"模式匹配搜索到的、尽可能长的字符串。
* 含义为零次或多次匹配前面的字符或子表达式。例如,zo* 匹配"z"和"zoo”。
. 字符匹配除"\r\n"之外的任何单个字符
package org.example;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ZhengZe {
public static void main(String[] args) throws Exception{
String regEx = "1.*?1";
String s = "100010000000000001";
Pattern pat = Pattern.compile(regEx);
Matcher mat = pat.matcher(s);
if(mat.find()){
System.out.println(mat.group(0));
}
}
}