java - How to test if a String contains both letter and number

前端 未结 7 1236
轻奢々
轻奢々 2020-12-16 01:07

I need a regex which will satisfy both conditions.

It should give me true only when a String contains both A-Z and 0-9.

Here\'s what I\'ve tried:

7条回答
  •  情话喂你
    2020-12-16 01:32

    Here is the regex for you

    Basics:

    Match in the current line of string: .

    Match 0 or any amount of any characters: *

    Match anything in the current line: .*

    Match any character in the set (range) of characters: [start-end]

    Match one of the regex from a group: (regex1|regex2|regex3)

    Note that the start and end comes from ASCII order and the start must be before end. For example you can do [0-Z], but not [Z-0]. Here is the ASCII chart for your reference

    Check the string against regex

    Simply call yourString.matches(theRegexAsString)

    Check if string contains letters:

    Check if there is a letter: yourString.matches(".*[a-zA-Z].*")

    Check if there is a lower cased letter: yourString.matches(".*[a-z].*")

    Check if there is a upper cased letter: yourString.matches(".*[A-Z].*")

    Check if string contains numbers:

    yourString.matches(".*[0-9].*")

    Check if string contains both number and letter:

    The simplest way is to match twice with letters and numbers

    yourString.matches(".*[a-zA-Z].*") && yourString.matches(".*[0-9].*")

    If you prefer to match everything all together, the regex will be something like: Match a string which at someplace has a character and then there is a number afterwards in any position, or the other way around. So your regex will be:

    yourString.matches(".*([a-zA-Z].*[0-9]|[0-9].*[a-zA-Z]).*")

    Extra regex for your reference:

    Check if the string stars with letter

    yourString.matches("[a-zA-Z].*")

    Check if the string ends with number

    yourString.matches(".*[0-9]")

提交回复
热议问题