开发者

Java RegEx replace

开发者 https://www.devze.com 2023-03-27 19:51 出处:网络
I need to use a replace function in Java: string.replace(myString,\"\"); myString values are for example javascript:r(0), javascript:r(23), javascript:l(5) etc. Just number is always different and the

I need to use a replace function in Java: string.replace(myString,""); myString values are for example javascript:r(0), javascript:r(23), javascript:l(5) etc. Just number is always different and there is r or l letter. What's the regular expression开发者_Go百科 to match it? Thanks


(FIXED) The regex you want is

"javascript:[rl]\\(\\d+\\)"

NOTE: The outer quotes aren't really part of the regex; they are part of the Java string you pass to Pattern.compile or directly to replace.

Here is a complete program you can try:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class PatternExample {
    private static final Pattern JS_PATTERN = Pattern.compile("javascript:[rl]\\(\\d+\\)");
    private static final String[] MESSAGES = {
        "Good javascript:r(5)",
        "Good javascript:l(50003843)",
        "Good javascript:r(1123934)",
        "Bad javascript:|(5)",
        "Bad javascript:r(53d)",
        "Bad javascript:l()",
    };
    public static void main(String[] args) {
        for (String s : MESSAGES) {
            Matcher matcher = JS_PATTERN.matcher(s);
            System.out.println(matcher.replaceAll(""));
        }
    }
}

Here is another version of the above program that calls replaceAll directly on the string instead of pre-compiling the pattern:

public class PatternExample {
    private static final String[] MESSAGES = {
        "Good javascript:r(0)",
        "Good javascript:l(50003843)",
        "Good javascript:r(1123934)",
        "Bad javascript:|(5)",
        "Bad javascript:r(53d)",
        "Bad javascript:l()",
    };
    public static void main(String[] args) {
        for (String s : MESSAGES) {
            System.out.println(s.replaceAll("javascript:[rl]\\(\\d+\\)", ""));
        }
    }  
}


The following regex will match it:

javascript:[rl]\(\d+\)
0

精彩评论

暂无评论...
验证码 换一张
取 消