NeroKamin
V2EX  ›  问与答

为什么同样的一段正则表达式, JS 和 Java 的匹配结果不一样呢?

  •  
  •   NeroKamin · Oct 17, 2024 · 7505 views
    This topic created in 769 days ago, the information mentioned may be changed or developed.
    const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d<>"'\\|])(?!.*[<>"'\\|])/;
    console.log(regex.test("AaBb123!@#"));
    // output: true
    
    public static void main(String[] args) {
            Pattern compile = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^a-zA-Z\\d<>\"'\\\\|])(?!.*[<>\"'\\\\|])");
            Matcher matcher = compile.matcher("AaBb123!@#");
            System.out.println(matcher.matches());
            // output: false
    }
    

    丢给 AI 也看不出什么问题,AI 的结论是两段代码输出都应该一样为 true

    7 replies  •  2024-10-18 09:08:25 +08:00
    revlis7
    revlis7
    Oct 17, 2024
    1
    \d 多了一个斜杠
    NeroKamin
    NeroKamin
    OP
    Oct 17, 2024
    2
    @revlis7 #1 改成\d 会报错
    nagisaushio
    nagisaushio
    Oct 18, 2024❤️1
    3
    java 的 matcher.matches 是尝试匹配整个字符串吧?你在 java 的正则后面加个 .* 就对了
    javaluo
    javaluo
    Oct 18, 2024
    4
    public static void main(String[] args) {
    Pattern compile = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^a-zA-Z\\d<>\"'\\\\|])(?!.*[<>\"'\\\\|])");
    Matcher matcher = compile.matcher("AaBb123!@#");
    System.out.println(matcher.matches()); }
    cheese
    cheese
    Oct 18, 2024
    5
    Pattern compile = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^a-zA-Z\\d<>\"'\\\\|])(?!.*[<>\"'\\\\|])");试试这段
    NeroKamin
    NeroKamin
    OP
    Oct 18, 2024
    7
    @nagisaushio #3 加上确实好使了。也就是说 js regexp.test 和 java matcher.matches 的意义是不一样的吗?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2563 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 50ms · UTC 12:09 · PVG 20:09 · LAX 04:09 · JFK 07:09
    ♥ Do have faith in what you're doing.