Reputation: 2755
I'm trying to match digits with at least 5 characters (for the whole string) connected by a hyphen or space (like a bank account number).
e.g
"12345-62436-223434"
"12345 6789 123232"
I should also be able to match
"123-4567-890"
The current pattern I'm using is
(\d[\s-]*){5,}[\W]
But i'm getting these problems.
I'm going to replace this so I only want to match digits, not the white-spaces and hypens.
When I get the match what I want to do is to mask it like the one below.
from "12345-67890-11121" to "*****-*****-*****"
or
from "12345 67890 11121" to "***** ***** *****"
My only problem is that I don't get to match it like what I want to.
Thanks!
Upvotes: 2
Views: 3924
Reputation: 521389
One option here is to take your existing pattern, and then add a positive lookahead which asserts that there are seven or more characters in the pattern. Assuming that there are two spaces or dashes in the account number, this will guarantee that there are five or more digits.
You can try using the following regex:
^(?=.{7,}$)((\\d+ \\d+ \\d+)|(\\d+-\\d+-\\d+))$
Test code:
String input = "123-4567-890";
boolean match = input.matches("^(?=.{7,}$)((\\d+ \\d+ \\d+)|(\\d+-\\d+-\\d+))$");
if (match) {
System.out.println("Match!");
}
If you need to first fish out the account numbers from a larger document/source, then do so and afterwards you can apply the regex logic above.
Upvotes: 1
Reputation: 8576
Maybe you want something like this:
(\d{5,})(?:-|\s)(\d{5,})(?:-|\s)(\d{5,})
EDIT:
(\d+)(?:-|\s)(\d+)(?:-|\s)(\d+)
Upvotes: 2
Reputation: 43169
This one might work for you (probably some false-positives, though):
\d[ \d-]{3,}\d
Upvotes: 2