简体   繁体   中英

Java regular expression for string containing at least one alphanumeric character, in any location

I am looking for a terse Java regular expression that can be used as an argument to the String.matches(…) method and it returns true if the string contains at least one alphanumeric character, in any location . I have tried a few things but nothing seems to work. As an example, I tried the following regex:

*[a-zA-Z0-9]+*

However, I get the following run-time exception:

Dangling meta character '*' near index 0
*[a-zA-Z0-9]+*
^

The String.matches method attempts to match the entire string to the regular expression. So an expression that matches any string with an alphanumeric in it would be: ".*\\\\w.*" Note that \\w includes the underscore character so if you don't want that included then stick with your more explicit pattern.

Alternatively you could use Pattern.find to just find "\\\\w" anywhere in your string.

The asterisk ('*') is not the symbol for matching any character, period ('.') is.

You need to change your regex to .[a-zA-Z0-9]+.


The asterisk is used to specify the count of the matched pattern:

[0-9]+ means at least one digit

[0-9]* means none, one ore more digits

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM