简体   繁体   English

为什么这个Java正则表达式不能编译?

[英]Why doesn't this Java regex compile?

I am trying to extract the pass number from strings of any of the following formats: 我试图从以下任何格式的字符串中提取传递号码:

PassID_132
PassID_64
Pass_298
Pass_16

For this, I constructed the following regex: 为此,我构建了以下正则表达式:

Pass[I]?[D]?_([\d]{2,3})

-and tested it in Eclipse's search dialog. - 在Eclipse的搜索对话框中测试它。 It worked fine. 它工作正常。

However, when I use it in code, it doesn't match anything. 但是,当我在代码中使用它时,它与任何东西都不匹配。 Here's my code snippet: 这是我的代码片段:

String idString = filename.replaceAll("Pass[I]?[D]?_([\\d]{2,3})", "$1");
int result = Integer.parseInt(idString);

I also tried 我也试过了

java.util.regex.Pattern.compile("Pass[I]?[D]?_([\\d]{2,3})")

in the Expressions window while debugging, but that says "", whereas 在调试时的表达式窗口中,但是说“”,而

java.util.regex.Pattern.compile("Pass[I]?[D]?_([0-9]{2,3})")

compiled, but didn't match anything. 编译,但没有匹配任何东西。 What could be the problem? 可能是什么问题呢?

而不是通过[I]?[D]?_([\\ d] {2,3})试试这个:

Pass(?:I)?(?:D)?_([\d]{2,3})

There's nothing invalid with your tegex, but it sucks. 没有什么无效您的tegex的,但它吮吸。 You don't need character classes around single character terms. 您不需要围绕单个字符术语的字符类。 Try this: 尝试这个:

"Pass(?:ID)?_(\\d{2,3})"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM