简体   繁体   中英

How do i check string to contain only letter(Uppercase & Lowercase) and at least one number only

I'm wondering how do i write a regex to check a string contain at least one uppercase and numbers and does not contain any symbols?

example:

String str = "%$!@asdas"

String str2 = "He110W0rLd"

I want it to reject str however accept str2 .

It give me this JEES 在此处输入图片说明

Based on @anubhava comment, try this:

As JAVA String:

"(?=.*[A-Z])(?=.*[0-9])[a-zA-Z\\d]+"

As Regular Expression:

(?=.*[A-Z])(?=.*[0-9])[a-zA-Z\d]+

This site can help http://www.regexplanet.com/advanced/java/index.html

Hello : No

He11o : Yes

heLl1o : Yes

hello : No

3424234 : No

UPDATE: The upper Regex would take HELLO1 as acceptable , because it is not forcing a lowercase, to add this check too the JAVA string would be:

"(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])[a-zA-Z\\d]+"
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexExample {

    public static void main(String[] args) {
        List<String> names = new ArrayList<String>();

        names.add("");
        names.add("%$!@asdas"); // Incorrect
        names.add("He110W0rLd");
        names.add("Techyshy");
        names.add("TechyShy123");
        names.add("Techy$hy123-"); // Incorrect

        String regex = "^[a-zA-Z0-9]+$";
        // Use "^[a-zA-Z0-9]*$"  if blank input is also a valid input. 

        Pattern pattern = Pattern.compile(regex);

        for (String name : names) {
            Matcher matcher = pattern.matcher(name);
            System.out.println(matcher.matches());
        }
    }
}

Output:

false
false
true
true
true
false

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