V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
NeroKamin
V2EX  ›  问与答

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

  •  
  •   NeroKamin · Oct 17, 2024 · 5340 views
    This topic created in 564 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
        1
    revlis7  
       Oct 17, 2024
    \d 多了一个斜杠
    NeroKamin
        2
    NeroKamin  
    OP
       Oct 17, 2024
    @revlis7 #1 改成\d 会报错
    nagisaushio
        3
    nagisaushio  
       Oct 18, 2024   ❤️ 1
    java 的 matcher.matches 是尝试匹配整个字符串吧?你在 java 的正则后面加个 .* 就对了
    javaluo
        4
    javaluo  
       Oct 18, 2024
    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
        5
    cheese  
       Oct 18, 2024
    Pattern compile = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[^a-zA-Z\\d<>\"'\\\\|])(?!.*[<>\"'\\\\|])");试试这段
    revlis7
        6
    revlis7  
       Oct 18, 2024   ❤️ 1
    NeroKamin
        7
    NeroKamin  
    OP
       Oct 18, 2024
    @nagisaushio #3 加上确实好使了。也就是说 js regexp.test 和 java matcher.matches 的意义是不一样的吗?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2916 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 09:11 · PVG 17:11 · LAX 02:11 · JFK 05:11
    ♥ Do have faith in what you're doing.