时间:2022-12-29 10:52:43 | 栏目:JAVA代码 | 点击:次
public static void main(String[] args) { /** * String str = "[Part 'name=1234567']"; */ String targetStr = "where 1=1 [and user_name like '%$user_name$%'] [and company_name like '%$company_name$%']"; String[] split = targetStr.split("]"); System.out.println("split==== " + split); String patternStr = "^[\\s\\S]{0,}\\[\\s{0,}and\\s{0,}[\\d\\W\\w]{1,}\\s{0,}[\\w]{1,}\\s{0,}\\W{0,}(\\$.+?\\$)\\W{0,}\\s{0,}\\s{0,}$"; // 正则表达式 Pattern pattern = Pattern.compile(patternStr); // 参数:要匹配的目标字符串 Map<String,String> map = new HashMap<String,String>(); map.put("$user_name$","user_value"); map.put("$company_name$","company_value"); map.put("$school_name$","$school_name$"); /*int groupCount = matcher.groupCount(); System.out.println("groupCount==== " + groupCount);*/ for (int i = 0;i<=split.length-1;i++) { Matcher matcher = pattern.matcher(split[i]); System.out.println("split[i]==== " + split[i]); boolean b = matcher.find(); if (b) { String key = matcher.group(1); for (Map.Entry<String,String> m : map.entrySet()){ String mapKey = m.getKey(); if (key.equalsIgnoreCase(mapKey)) { System.out.println("key==== " + key ); /*String bigGroup = matcher.group(); System.out.println("bigGroup==== " + bigGroup);*/ targetStr = targetStr.replace(key,m.getValue()); // System.out.println("targetStr after replace innner==== " + targetStr); } } } // System.out.println("targetStr after replace outer==== " + targetStr); } System.out.println("targetStr after replace final==== " + targetStr); }
java匹配字符串表达式在我们数据处理方面是及其重要的,现在就把我这几天数据处理比较常用的向大家介绍一下,常规的一些匹配方式就不介绍了,我们来学习一些特殊的
Pattern pattern = Pattern.compile("采购(人名称|人单位|名称).*"); Matcher matcher = pattern.matcher("采购名称乒位"); String dateStr = null; if (matcher.find()) { dateStr = matcher.group(0); System.out.println(dateStr); }
运行结果如下:
(1)匹配中文字符
Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]"); Matcher matcher = pattern.matcher("2322购购购购232323"); String dateStr = null; if (matcher.find()) { dateStr = matcher.group(0); System.out.println(dateStr); }
运行结果如下:
(2)匹配从规定字符开始所有非换行字符
Pattern pattern = Pattern.compile("1.*"); Matcher matcher = pattern.matcher("2312购购购购232323"); String dateStr = null; if (matcher.find()) { dateStr = matcher.group(0); System.out.println(dateStr); }
运行结果如图:
(3)使用字符串数组匹配多个条件匹配字符串,这是我在实习进行处理数据的一个例子,希望有助于大家理解:
(4)对于字符串匹配查找多个符合条件的字符字串,我们用到group(),
group(num=0)
: 匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。 groups()
: 返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。