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. 文件替换:
写一个程序, 读入 template.txt 和 env.properties
将template 中 ${NAME}表达式里的变量替换为env里设定的值. 然后输出到一个文件里.
第一个变量是: ${webwork.jsp.include_flush}
第二个变量是: ${webwork.i18n.encoding}
第三个第四个变量分别是: ${webwork.ui.templateSuffix}和${webwork.ui.notfound}
匹配${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)"等.