regex detect word with 2+ number and 2+ character

Mirko Cianfarani :

I need one regular expression for detect words with length 8 characters that contain 2+ numbers and 2+ characters (no special characters ).

I am near the solution and I did the regex on regex101.com .

The problem are the words that contains one number that not should be releveant for my regex.

I discarded all words with characters that contain min 7 characters with (?![A-Za-z]{7,}) .

I discarded all words with numbersthat contain min 7 numbers with (?![\d]{7,}) .

And I discarded the words that contain min 2 numbers and 2 characters (?=[a-zA-Z\d]{2})[A-Za-z\d]{8}.

Why vaff8loe is matched?

I created this regular expression because after I hae to replace the entire word with ******* . Like:

papave23 ciao il mio pin papaver1 è reeredji332ji con vaff8loe 1234567o 123t123t papavero 9o 123t123y

After with replace("regex","********")

********ciao il mio pin papaver1 è reeredji332ji con ******** 1234567o ******** papavero 9o ********
Andreas :

Use 2 zero-width positive lookaheads:

(?=.*?[a-zA-Z].*?[a-zA-Z])    Must contain 2 ASCII letters
(?=.*?[0-9].*?[0-9])          Must contain 2 digits
[a-zA-Z0-9]{8}                Must be exactly 8 letters and/or digits

Add ^ and $ if not using matches() for running the regex.

That means a full regex of:

^(?=.*?[a-zA-Z].*?[a-zA-Z])(?=.*?[0-9].*?[0-9])[a-zA-Z0-9]{8}$

For best performance, replace the . pattern with a negative character class. In that case you might want to shorten it with a repeating non-capturing group:

(?=(?:[^a-zA-Z]*[a-zA-Z]){2})
(?=(?:[^0-9]*[0-9]){2})

UPDATE

As question was updated to say that regex is needed to replace such words with *'s, the ^ and $ anchors should be changed to \b word boundary patterns, and the negative character classes must be changed to only skip valid characters:

s = s.replaceAll("\\b(?=(?:[0-9]*[a-zA-Z]){2})(?=(?:[a-zA-Z]*[0-9]){2})[a-zA-Z0-9]{8}\\b", "********");

See regex101 for demo.

Note that vaff8loe in the given example only contains 1 digit, so should not be replaced.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113394&siteId=1