例子1,正则匹配")"或者"\)"的问题
String regex1 = "\\)"; //前面两个\\代表一个\,加上)刚好就是一个"\)" String regex2 = "\\\\\\)";//对于一个括号的转义,意思就是匹配一个)的正则表达式 System.out.println("regex1: " + regex1); System.out.println("regex2: " + regex2); String input1 = ")"; String input2 = "\\)"; System.out.println("input1: " + input1); System.out.println("input2: " + input2); System.out.println(Pattern.compile(regex1).matcher(input1).matches()); System.out.println(Pattern.compile(regex2).matcher(input2).matches());
regex1: \) regex2: \\\) input1: ) input2: \) 注:这里打印出来的才是我们真是的需要的匹配的数据,程序中体现的是为了通过编译的一个程序规范写法; true true
当然要匹配一个"\"或者"\\",就得这么写了:
String regex1 = "\\\\"; String regex2 = "\\\\\\\\"; System.out.println("regex1: " + regex1); System.out.println("regex2: " + regex2); String input1 = "\\"; String input2 = "\\\\"; System.out.println("input1: " + input1); System.out.println("input2: " + input2); System.out.println(Pattern.compile(regex1).matcher(input1).matches()); System.out.println(Pattern.compile(regex2).matcher(input2).matches());
regex1: \\ regex2: \\\\ input1: \ input2: \\ true true
例子2,替换一个"\"为两个"\\",根据"\"分割路劲
String path = "c\\:wo\\de\\lujin"; String regex3 = "\\\\"; String regex4 = "\\\\\\\\"; System.out.println("path替换前:" + path); System.out.println("regex3: " + regex3); System.out.println("regex4: " + regex4); String[] pathArr = path.split(regex3); System.out.println(Arrays.asList(pathArr)); System.out.println("path替换后:" + path.replaceAll(regex3, regex4));
path替换前:c\:wo\de\lujin regex3: \\ regex4: \\\\ [c, :wo, de, lujin] path替换后:c\\:wo\\de\\lujin
分享:
崇尚极简,热爱技术,喜欢唱歌,热衷旅行,爱好电子产品的一介码农。
联系QQ:58742094
联系电话:
工作邮箱:
当你的才华还撑不起你的野心的时候,你就应该静下心来学习,永不止步!
人生之旅历途甚长,所争决不在一年半月,万不可因此着急失望,招精神之萎葸。
Copyright 2015- 芒果酷(mangocool.com) All rights reserved. 湘ICP备14019394号
免责声明:本网站部分文章转载其他媒体,意在为公众提供免费服务。如有信息侵犯了您的权益,可与本网站联系,本网站将尽快予以撤除。