简体   繁体   中英

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. 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. You don't need character classes around single character terms. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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