正则表达式的几个用途

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)"等.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值