zoukankan      html  css  js  c++  java
  • JAVA、C#中使用正则表达式替换字符串

    进来在项目中碰到一个字符串替换问题,要替换的内容格式相对比较固定,里面包含时间为变化值,想到了用正则表达式替换,一直学,一直不会写,也是醉了


    要调换掉的内容如下:

    (折扣适用范围:起始日期:20210101,终止日期:20211231)
    (折扣适用范围:起始日期:20200101,终止日期:2020.12.31)

    主要是这两种组合,可能是独立段落,也可能是嵌套在语句中 c#代码实现:
    public string ReplaceNote(string note)
            {
                string regexStr = "([(]折扣适用范围:起始日期:)([0-9][0-9][0-9][0-9])(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01]),终止日期:([0-9][0-9][0-9][0-9])(\.?)(0[1-9]|1[012])(\.?)(0[1-9]|[12][0-9]|3[01])[)]";
                Regex reg = new Regex(regexStr);
    
                if (!string.IsNullOrEmpty(note))
                {
                    string modifiedNote = reg.Replace(note, "");
                    return modifiedNote;
                }
                return note;
            }
    java 代码实现:
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    private String ReplaceNote(String note){
            String pattern = "([(]折扣适用范围:起始日期:)([0-9][0-9][0-9][0-9])(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01]),终止日期:([0-9][0-9][0-9][0-9])(\.?)(0[1-9]|1[012])(\.?)(0[1-9]|[12][0-9]|3[01])[)]";
            Pattern r = Pattern.compile(pattern);
            Matcher matcher = r.matcher(note);
            while(matcher.find()){
                String reeStr=matcher.replaceAll("");
                return reeStr;
            }
            return note;
        }

    正则表达式说明:

    //匹配 20201212 
    ([0-9][0-9][0-9][0-9])(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])  
    //匹配 2020.12.12
    ([0-9][0-9][0-9][0-9])(\.?)(0[1-9]|1[012])(\.?)(0[1-9]|[12][0-9]|3[01])
    最后分享一个正则图形化工具:regexper.com
  • 相关阅读:
    Spring配置自动加载执行多次的解决方法
    获取Excel文件内容,0307通用
    将Json转实体
    将实体转换为map
    Json数据转Map
    获取随机字符串
    将长内容分割,用双主键进行存储
    解决win10开机出现C:WIndowssystem32configsystemprofileDesktop不可用 问题
    2016.2.22
    云中行走
  • 原文地址:https://www.cnblogs.com/buyixiaohan/p/15465216.html
Copyright © 2011-2022 走看看