简体   繁体   English

用于数字和短划线的Java正则表达式

[英]Java regular expression for digits and dashes

I need a regular expression which matches lines with only 4(four) hyphens and 13 digits(0-9). 我需要一个正则表达式,它匹配只有4(4)个连字符和13个数字(0-9)的行。 The order is undefined. 订单未定义。 I have regex like: 我有正则表达式:

^([0-9\u2013-]{17})$

But, when I receive strings as 但是,当我收到字符串时

----123456789---- or 1-2-3-4-5-6-7-8-9 

matching is true but it must be false for me. 匹配是真的,但对我来说一定是假的。

Could you please explain what I need use in order to matches were only with strings like 123-345-565-45-67 or 123-1-34-5435-45- or ----1234567890123 etc? 你可以解释我需要使用什么才能匹配只有123-345-565-45-67 or 123-1-34-5435-45- or ----1234567890123 etc?字符串123-345-565-45-67 or 123-1-34-5435-45- or ----1234567890123 etc?

Try this regex: 试试这个正则表达式:

^(?=(?:[^-]*-){4}[^-]*$)(?=(?:\D*\d){13}\D*$).*$

Click for Demo 单击“演示”

Explanation: 说明:

  • ^ - asserts the start of the line ^ - 断言该行的开头
  • (?=(?:[^-]*-){4}[^-]*$) - positive lookahead to make sure that there are only 4 occurrences of - present in the string (?=(?:[^-]*-){4}[^-]*$) - 正向前瞻以确保字符串中只出现4次-出现
  • (?=(?:\\D*\\d){13}\\D*$) - positive lookahead to make sure that there are 13 occurrences of a digit present in the string (?=(?:\\D*\\d){13}\\D*$) - 正向前瞻以确保字符串中出现13个数字
  • .* - once the above 2 lookaheads are satisified, match 0+ occurrences of any character except a newline character .* - 一旦满足上述2个前瞻,匹配除换行符之外的任何字符的0+次出现
  • $ - asserts the end of the line $ - 断言该行的结尾

Escape \\ with another \\ in JAVA 在JAVA中使用另一个\\逃脱\\

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

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