Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid regular expression : Dangling meta character "*"

Tags:

java

regex

I am creating an identification window with login and username for JavaFX, and I am using regex to make sure that the password contains at least one special character and one digit.

This is the regular expression I'm using

newValue.matches("*\\d+.*\\W+.*")

It works on testing sites online however I am getting and error while I enter any input in the textfield. Here is the segment of code I am using:

public void progressBarHandler() {
    login.textProperty().addListener((observable, oldValue, newValue) -> {
        if(newValue.matches("*\\d+.*\\W+.*")) {
            passState.textProperty().set("Bad");
        }
        else passState.textProperty().set("Ok");
    });
}

Whenever I run the code and I write something in the textfield login I get this error:

Exception in thread "JavaFX Application Thread" java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
like image 691
princedavinci Avatar asked Apr 09 '26 04:04

princedavinci


2 Answers

The * quantifier "repeats" (quantifies) the pattern it modifies zero or more times in a greedy way (allows the regex engine to "take" (=consume) as many chars as it can with the given pattern). If * or any other quantifier appears at the start of a pattern, there is no pattern the quantifier can modify, and the error appears.

That is, *abc* glob pattern used as a regex will produce this same issue, as well as {1,}abc.*, +abc.* or {5}+abc.*, etc.

You may fix the pattern by simply adding a dot in front of the * here since you expect to match a string that contains a pattern digits...non-word chars...:

newValue.matches(".*\\d+.*\\W+.*")
//                ^

However, a better, more efficient pattern here would be

newValue.matches("\\D*\\d\\w*\\W.*")

It matches

  • start of string (matches requires a full string match)
  • \D* - zero or more non-digit chars
  • \d - a digit
  • \w* - 0 or more word chars
  • \W - a non-word char
  • .* - any zero or more chars other than line break chars as many as possible.
  • end of string (matches requires a full string match).
like image 84
Wiktor Stribiżew Avatar answered Apr 10 '26 17:04

Wiktor Stribiżew


In regular expressions, the Kleene star * means "zero or more matches of the preceding character (class) or group". But in your case, there is nothing preceding, the star is the first character in your regex string. That's what the error indicates.

If you actually want to match an asterisk you have to escape it with backslashs:

"\\*\\d+.*\\W+.*"
like image 32
Thomas Avatar answered Apr 10 '26 17:04

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!