-1

I want to make a regular expression to the following string :

String s = "fdrt45B45";     // s is a password (just an example) with only 
                            // letters and digits(must have letters and digits)

I tried with this pattern:

String pattern= "^(\\w{1,}|\\d{1,})$";     //but it doesn't work 

I want to get a not match if my password doesn't contains letters or digits and a match if its contains both.

I know that: \w is a word character: [a-zA-Z_0-9] and \d is a digit: [0-9], but i can not mix \w and \d to get what i want. Any help or tips is very appreciated for a newbie.

whoknows
  • 296
  • 1
  • 4
  • 18
dustin
  • 3
  • 5

2 Answers2

1

A positive lookahead would do the trick :

String s = "fdrt45B45";
System.out.println(s.matches("(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z0-9]+"));
Mena
  • 47,782
  • 11
  • 87
  • 106
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Thanks, it works like a charm and I am trying to understand the expression. – dustin Aug 27 '15 at 09:13
  • @dustin - `(?=.*[something])` is called *positive look ahead*. It looks for *something* but doesn't move the *pointer / reference* to point to something. The first 2 `?=` checks start from length `0` . Your actual character *capture* starts from `[a-zA-Z0-9]`. The first 2 expressions are *look and forget* kind. Got it? – TheLostMind Aug 27 '15 at 09:17
0

You should be able to use the following regex to achieve what you want. This uses a positive look ahead and will match any string containing at least one letter and at least one number.

^(?=.*\\d)(?=.*\\w).*
olambert
  • 1,075
  • 2
  • 7
  • 10
  • 1
    Please note that `\w` doesn't mean "all letters", it means "all letters, digits, and underscore" (`[a-zA-Z_0-9]`). So your regex is matching an unwanted password. [Documentation](https://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html) – BackSlash Aug 27 '15 at 09:07
  • @olambert: it dosen't work with only digits (i have a match with only digits), otherwise it is fine. – dustin Aug 27 '15 at 09:11
  • OK, I think I misunderstood what you were trying to do - I thought you wanted to enforce that the password had both letters and digits. If you just want to match a password with letters or digits, you could just use `^[0-9A-Za-z]+$` – olambert Aug 27 '15 at 09:19
  • @olambert: I think I misunderstood what you were trying to do - I thought you wanted to enforce that the password had both letters and digits...**this is what i want to**, but with: `^(?=.*\\d)(?=.*\\w).*` i get a match with only digits!! - **Thanks anyway for trying to help me** – dustin Aug 27 '15 at 09:35