1

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 enter image description here

isme
  • 190
  • 2
  • 3
  • 18

2 Answers2

1

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]+"
Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
  • I don't know about JAVA string.matches actually just the regular expression this why, i hope it is working now – Mi-Creativity Oct 23 '15 at 18:58
  • Ok!! finally god!!! was figuring this out keep on reading and i don't understand the regex.. haha thank you so much JEES && anubhava – isme Oct 23 '15 at 18:59
0
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