【正则表达式】java应用正则表达式

发布者:Love Lenka
发布于:2018-05-12 02:00

一:简单应用

 /**
     *
     * '
     * &
     * '
     * &
     * &
     * '
     * '
     * '
     * sources=sdcg'hde&xyz'dfa&&ad'''
     * result=sdcghdexyzdfaad

     */
    public static void main(String[] args) {
        String regex="'|&";
        Pattern pattern=Pattern.compile(regex);
        String sources="sdcg'hde&xyz'dfa&&ad'''";
        Matcher matcher=pattern.matcher(sources);
        while(matcher.find()){
            System.out.println(matcher.group());
        }
        String result=matcher.replaceAll("");
        System.out.println("sources="+sources);
        System.out.println("result="+result);
    }

 

二:特例:“\”在java的正则表达式需要写成“\\\\”

 /**
     * \
     * &
     * \
     * &
     * &
     * sources=sdcg\hde&xyz\dfa&&ad'''
     * result=sdcghdexyzdfaad'''
     * 
     * @param args
     */
    public static void main(String[] args) {
        String regex="\\\\|&";
        Pattern pattern=Pattern.compile(regex);
        String sources="sdcg\\hde&xyz\\dfa&&ad'''";
        Matcher matcher=pattern.matcher(sources);
        while(matcher.find()){
            System.out.println(matcher.group());
        }
        String result=matcher.replaceAll("");
        System.out.println("sources="+sources);
        System.out.println("result="+result);
    }
View Code

 


声明:该文观点仅代表作者本人,转载请注明来自看雪