使用replaceAll()替换匹配模式的一部分

时间:2019-03-01 04:26:30

标签: java regex

捕获网址中查询值的有效模式可能是

\(?|&\)[^=]+=([^&]+)

如何使用replaceAll替换网址中查询的所有

还是在这里使用其他技巧?

案例-1

Actual: https://stackoverflow.com/questions/54937940?a=5
Expected: https://stackoverflow.com/questions/54937940?a=XX

案例-2

Actual: https://stackoverflow.com/questions/54937940?a=5&b=7
Expected: https://stackoverflow.com/questions/54937940?a=xx&b=xx

案例-3

Actual: *266 open() "/usr/local/nginx/html/user-accounts/malphas/check" failed (2: No such file or directory), client: 10.254.3.0, server: ji, request: "GET /user-accounts/malphas/check?sid=ExecAuthoritySetting HTTP/2.0", host: "jilcom", referrer: "https://jicom/user-accounts/authority/authoritysettings/authoritysetting/detail?sid=ExecAuthoritySetting&roleId=1812""
tid"
Expected: *266 open() "/usr/local/nginx/html/user-accounts/malphas/check" failed (2: No such file or directory), client: 10.254.3.0, server: ji, request: "GET /user-accounts/malphas/check?sid=xx HTTP/2.0", host: "jilcom", referrer: "https://jicom/user-accounts/authority/authoritysettings/authoritysetting/detail?sid=xx&roleId=xx""
tid"

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:3)

由于您只想匹配params的值,可以使用环顾四周使用此正则表达式来匹配值,然后将其替换为xx或所需的任何内容。

(?<=[&=])[^=&"\n ]*(?=[&" ]|$)

Demo

查看此Java代码

List<String> list = Arrays.asList("https://stackoverflow.com/questions/54937940?a=5",
            "https://stackoverflow.com/questions/54937940?a=5&b=7", "*266 open() \"/usr/local/nginx/html/user-accounts/malphas/check\" failed (2: No such file or directory), client: 10.254.3.0, server: ji, request: \"GET /user-accounts/malphas/check?sid=ExecAuthoritySetting HTTP/2.0\", host: \"jilcom\", referrer: \"https://jicom/user-accounts/authority/authoritysettings/authoritysetting/detail?sid=ExecAuthoritySetting&roleId=1812\"\"tid\"");
    list.forEach(x -> {
        System.out.println(x + " --> " + x.replaceAll("(?<=[&=])[^=&\"\\n ]*(?=[&\" ]|$)", "xx"));
    });

打印

https://stackoverflow.com/questions/54937940?a=5 --> https://stackoverflow.com/questions/54937940?a=xx
https://stackoverflow.com/questions/54937940?a=5&b=7 --> https://stackoverflow.com/questions/54937940?a=xx&b=xx
*266 open() "/usr/local/nginx/html/user-accounts/malphas/check" failed (2: No such file or directory), client: 10.254.3.0, server: ji, request: "GET /user-accounts/malphas/check?sid=ExecAuthoritySetting HTTP/2.0", host: "jilcom", referrer: "https://jicom/user-accounts/authority/authoritysettings/authoritysetting/detail?sid=ExecAuthoritySetting&roleId=1812""tid" --> *266 open() "/usr/local/nginx/html/user-accounts/malphas/check" failed (2: No such file or directory), client: 10.254.3.0, server: ji, request: "GET /user-accounts/malphas/check?sid=xx HTTP/2.0", host: "jilcom", referrer: "https://jicom/user-accounts/authority/authoritysettings/authoritysetting/detail?sid=xx&roleId=xx""tid"