正则表达式的几个用途
1)参数校验 后端通过Regular Expression验证前端传来的数据 Pattern passwordPattern = Pattern.compile("^w{8,32}$"); Matcher passwordMatcher = passwordPattern.matcher(newPassword); if(!passwordMatcher.matches()) { codeMessage = new CodeMessageImpl(4,"密码不规范,只能包含字符、数字和下划线!",null); } 2.取特定字符串 matcher.group(int i) 会取出相关的子串.group是针对()来说的,group(0)就是指的整个串,group(1) 指的是第一个括号里的东西,group(2)指的第二个括号里的东西。 在执行group()之前必须要执行cityCodeMatcher.find(),否则会报异常:java.lang.IllegalStateException: No match found. public static File getHotelNumberInfo(File hotelInfoFile) throws IOException { List<String> lines = Files.readLines(hotelInfoFile,Charsets.UTF_8); List<String> cityCodes = new LinkedList<String>(); int lineSize = lines.size(); Pattern cityCodePattern=Pattern.compile("(.+)_[0-9]+"); for (int i = 0; i < lineSize; i++) { Matcher cityCodeMatcher = cityCodePattern.matcher(lines.get(i)); cityCodeMatcher.find(); logger.info(cityCodeMatcher.group(1)); } return null; } "(.+)_[0-9]+"匹配了字符串"shanghai_city_7208 上海全季酒店淮海路店"中的"shanghai_city_7208". 而group(1)返回了"shanghai_city". "^w{8,32}$"会对字符串的首尾进行整串匹配. 3. 文件替换: 匹配${webwork.i18n.encoding}的正则表达式是:"${(.+?)}" ?标识非贪婪式匹配,如果不加"?","${(.+)}",${webwork.i18n.encoding}}}}}}}}}}}}}}}}整个串都会被匹配. (.+)[=?](.+)$ 可以匹配webwork.ui.templateSuffix=jsp,并且group(1)为webwork.ui.templateSuffix,group(2)为jsp. 4.正则表达式如何匹配单个汉字? 5. "$natureOrder(([1-9]d*))"匹配"$natureOrder(2980)""$natureOrder(2984)"等. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |