目录
单字符匹配符 .
. 匹配字符可以匹配任意一个字符。 . 例如 : a,b,c , . ,'等。
测试实例1
被匹配字符串
private final static String testStr1 = "This is a matched string";
匹配公式1:
String pattern = "is";
匹配公式2:
String pattern2 = ".is";
匹配公式3:
String pattern3 = ".is.";
匹配公式4:
String pattern4 = ".is..";
匹配结果:
测试实例2【配置特殊字符.】
被匹配字符串:
private final static String testStr3 = "This is a matched string 【isa.bbb】";
匹配公式:【\\第一个是转译 第二个 \ 字符,第二个字符转译 . 】
String pattern5 = ".is.\\..";
匹配结果:
可以 使用 \ 转译 . 字符,此时的 . 不再是正则表达式的单字符匹配符 ,而是普通的字符 .
下面有更加明显的测试结果:
测试代码【Java】:
package com.kgo.javaregular.character;
import cn.hutool.core.util.ReUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author keepgoon
* @Description: TODO
* @date 2019/9/3021:47
*/
public class SingleCharacter {
private static Logger log = LoggerFactory.getLogger(SingleCharacter.class);
private final static String testStr1 = "This is a matched string";
private final static String testStr2 = "this is test character string \n this is next str";
private final static String testStr3 = "This is a matched string 【isa.bbb】";
private final static String testStr4 = "This is a matched string 【isa*bbb】";
public static void main(String[] args) {
String pattern = "is";
String pattern2 = ".is";
String pattern3 = ".is.";
String pattern4 = ".is..";
String pattern5 = ".is.\\..";
String pattern6 = ".is.\\*.";
log.debug("===============匹配公式1 =======================");
find(pattern,testStr1);
log.debug("\n==============匹配公式2 =========================");
find(pattern2,testStr1);
log.debug("\n==============匹配公式3 =========================");
find(pattern3,testStr1);
log.debug("\n==============匹配公式4 =========================");
find(pattern4,testStr1);
log.debug("\n==============匹配公式 特殊字符 . =========================");
find(pattern5,testStr3);
log.debug("\n==============匹配公式 特殊字符 . =========================");
find(pattern6,testStr3);
log.debug("\n==============匹配公式 特殊字符 . =========================");
find(pattern6,testStr4);
}
private static String length(String printStr){
return StringUtils.rightPad(printStr,15," ") + " : {}";
}
private static void find(String pattern,String matchedStr){
log.debug(" 正则表达式 【 {} 】; 被匹配的字符串 【 {} 】" ,pattern,matchedStr);
log.debug(length("findAll"),ReUtil.findAll(pattern,matchedStr,0));
log.debug(length("count"), ReUtil.count(pattern,matchedStr));
log.debug(length("contains"), ReUtil.contains(pattern,matchedStr));
//log.debug(length("contains"), ReUtil.get);
}
private static void find(Pattern pattern,String matchedStr){
log.debug(" 正则表达式 【 {} 】; 被匹配的字符串 【 {} 】" ,pattern,matchedStr);
log.debug(length("findAll"),ReUtil.findAll(pattern,matchedStr,0));
log.debug(length("count"), ReUtil.count(pattern,matchedStr));
log.debug(length("contains"), ReUtil.contains(pattern,matchedStr));
//log.debug(length("contains"), ReUtil.get);
}
}
编程技术
编程语言 | java |
正则匹配 | 开源工具集 hutool |
打印 | logback |
字符串格式化 | lang3 |