简体   繁体   中英

Java matches doesn't match

Could someone explain why the following statement in java returns false?

boolean results = "123/#".matches("\\d/#")

I tried to escape the forward slash and the pound sign, but this was being marked as redundant..

String.matches() in Java requires the full string to match the regex, as if it was bounded with ^ ... $ . So imagine that you're actually testing the regex ^\\d/#$ here.

To allow the string to contain anything else before/after, you must explicitly allow that in the regex using .* (anything), for example:

boolean results = "123/#".matches(".*\\d/#.*")

\\d匹配一个数字,如果要匹配1个或多个,则添加一个量词\\d+

boolean results = "123/#".matches("\\d+/#")

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