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
posted @ 2021-10-26 12:52  天北涯  阅读(331)  评论(0编辑  收藏  举报