简体   繁体   中英

Regex to match N number of digits ignoring break lines only

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

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

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