匹配N个数字,忽略换行符的正则表达式

huangapple go评论77阅读模式
英文:

Regex to match N number of digits ignoring break lines only

问题

我需要在Java中构建一个正则表达式,匹配N个数字,忽略换行。请参考下面的示例:

以下是字符串:

1234567
891011234

我找到了一个解决方案,建议按照以下方式进行:

(\d\D*){16}

但这不起作用,因为它会匹配到这个:

1234567smth
891011234

甚至在我使用空格而不是"smth"时也会匹配,而我不希望出现这种情况。

请注意,换行可以出现在数字序列的任何部分,所以表达式也应该匹配以下情况:

123
4567891011234

谢谢

英文:

I need to build a regex in Java that matches N number of digits ignoring Line Breaks.
Please see the example below:

Here is string

1234567
891011234

I found a solution asking to do this way:

(\d\D*){16}

It doesn't work because it would match this>

1234567smth
891011234

Or even match if I have a White Space instead of "smth", and I don't want this..

Please notice that the line break can be in any part of the sequence of digits

So the expression should match this also:

123
4567891011234

Thank you

答案1

得分: 0

尝试一下这个,它会匹配16位数字,但允许数字中间有任意数量的换行符:

str.matches("(\\d\\R*){16}")

请注意,\R 表示 "任何 Unicode 换行序列"。

如果要在数字中最多允许1个换行符,将 * 改为 ?


"1234567\n891011234".matches("(\\d\\R*){16}") // true

"1234567\n8910112349999".matches("(\\d\\R*){16}") // false
"1234567\n891011234foo".matches("(\\d\\R*){16}") // false
"1234567\n89101123".matches("(\\d\\R*){16}") // false
英文:

Try this, which match 16 digits, but allows any number of newlines within the number:

str.matches("(\\d\\R*){16}")

fyi, \R means "any Unicode linebreak sequence"

To allow at most 1 newline within the digits, change * to ?.


"1234567\n891011234".matches("(\\d\\R*){16}") // true

"1234567\n8910112349999".matches("(\\d\\R*){16}") // false
"1234567\n891011234foo".matches("(\\d\\R*){16}") // false
"1234567\n89101123".matches("(\\d\\R*){16}") // false

huangapple
  • 本文由 发表于 2020年8月19日 06:56:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63477738.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定