简体   繁体   English

java.matches-method中的正则表达式模式

[英]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. 每个X是一个数字。

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: 我不确定,但我认为您必须在Java中加倍转义,所以:

^\\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 .) \\\\ Java需要两次转义(对于\\ d和。)
  • \\d matches any single number (0-9) \\ d匹配任何单个数字(0-9)
  • {X} means the preceding pattern chunk must occur X times, {X,Y} also works if you're flexible {X}表示前面的模式块必须出现X次,{X,Y}如果您很灵活也可以使用

Yes, your implementation looks great! 是的,您的实现看起来很棒!

Also note, you can remove the start/end tags if you need to match anywhere in a string. 另请注意,如果需要在字符串中的任何位置进行匹配,则可以删除开始/结束标签。

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

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