0

I need to verify a password using reqex. I have written one and tested it in this checker and it works: http://www.nvcc.edu/home/drodgers/ceu/resources/test_regexp.asp

But when I add it to my Java application, it fails.

Regex in regex checker:(\D+)(\d+)(\D+)(.*)

Regex in java: (\\D+)(\\d+)(\\D+)(.*)

Test string: 1Hello2

This passes in the online checker but fails in Java.

Does anyone know why?

I want the regex to match any password that has a number in its middle (can have them at the start and end too).

I need 2 seperate regex: one that matches digits in the middle (pass1word or 1pass1word or 1pass1word) and also a regex that matches a digit at the start or end (1password or password1 NOT pass1word1 because that is in the string category).

11
  • 2
    It doesn't pass in the online checker, and I know why. Namely, \D means a non-digit character. To match anything with a number in the middle, use something like '.+\d+.*'. Commented Mar 28, 2012 at 13:57
  • @Lev: I think you mean .*\d.*. Commented Mar 28, 2012 at 14:04
  • @NiklasB, you're right. It must have the same effect though. Commented Mar 28, 2012 at 14:07
  • @Lev: No, even after the edit it wouldn't match 1hello for example, although it's a valid password according to OP. Commented Mar 28, 2012 at 14:08
  • @NiklasB: ohhh, I misread (misunderstood) your comment. The regex I actually mean is '.+\d.+' (too late to edit the first comment now). Your regex matches any password with a digit in it. Mine matches any with a digit in the middle, which is how I understand the last sentence of the question. Commented Mar 28, 2012 at 14:14

1 Answer 1

2

Your regex requres:

  1. not digit (1 or more times) \D+
  2. 1 or more digits
  3. One or more non-digits \D+
  4. Any character(s) 0 or more times.

Your example contains

  1. 1 Digit
  2. 5 non-digits
  3. 1 digit

I think it is obvious that it does not match the regex: the first element \D+ fails because digit appears in the beginning.

Sign up to request clarification or add additional context in comments.

1 Comment

My solution in the end: Match strong (\\d*)(\\D+)(\\d+)(\\D+)(.*). Match medium: (\\d+)(\\D+)") || (\\D+)(\\d+)") || (\\d+)(\\D+)(\\d+)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.