简体   繁体   中英

regex pattern in java.matches-method

I need to get the regex pattern for the following sequence of numbers:

X.XXX.XXX-X 

Every X is one number.

I've already tried:

pattern: `partnerNumberOnFirstPage = "*.*.*-*"`

if (stringContent.matches(partnerNumberOnFirstPage)){
    return true;
} else {
    return false;
}

How can I do that? And do I implement it right? I don't want to use * because I need exactly the number of numbers.

How about:

^\d\.\d\d\d\.\d\d\d-\d$

I'm not sure but I think you have to double escape in java, so:

^\\d\\.\\d{3}\\.\\d{3}-\\d$

Lots of ways:

\d\.\d{3}\.\d{3}-\d

or

\d(?:\.\d{3}){2}-\d
^\\d\\.\\d{3}\\.\\d{3}-\\d$
  • ^ matches the start of a string
  • $ matches the end of a stringg
  • \\\\ java requires a double escape (for \\d and .)
  • \\d matches any single number (0-9)
  • {X} means the preceding pattern chunk must occur X times, {X,Y} also works if you're flexible

Yes, your implementation looks great!

Also note, you can remove the start/end tags if you need to match anywhere in a string.

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