Jude KIM
Jude KIM

Reputation: 119

Check a string contains at least one Unicode letter using regex

I want such a validation that My String must be contains at least one Unicode letter. The character that will evaluate Character.isLetter() to true.

for example i want

~!@#$%^&*(()_+<>?:"{}|\][;'./-=` : false
~~1_~ : true
~~k_~ : true
~~汉_~ : true

I know i can use for-loop with Character.isLetter(), but i just don't want to do it.

And This is totally different from this since it only checks for the English alphabets, but in my case is about one unicode letter. It's not a same at all.

Upvotes: 0

Views: 443

Answers (1)

Mark Melgo
Mark Melgo

Reputation: 1478

You can try to use this regex "\\p{L}|[0-9]"

To better understand Unicode in Regex read this.

Usage code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String args[]) {
        // String to be scanned to find the pattern.
        String line = "~!@#$%^&*(()_+<>?:\"{}|\\][;'./-=`";
        String pattern = "\\p{L}|[0-9]"; // regex needed

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);
        System.out.print("String \"" + line + "\" results to ");
        if (m.find()) {
            System.out.println("TRUE -> Found value: " + m.group(0));
        } else {
            System.out.println("FALSE");
        }
        line = "~~1_~";
        m = r.matcher(line);
        System.out.print("String \"" + line + "\" results to ");
        if (m.find()) {
            System.out.println("TRUE -> Found value: " + m.group(0));
        } else {
            System.out.println("FALSE");
        }
        line = "~~k_~";
        m = r.matcher(line);
        System.out.print("String \"" + line + "\" results to ");
        if (m.find()) {
            System.out.println("TRUE -> Found value: " + m.group(0));
        } else {
            System.out.println("FALSE");
        }
        line = "~~汉_~";
        m = r.matcher(line);
        System.out.print("String \"" + line + "\" results to ");
        if (m.find()) {
            System.out.println("TRUE -> Found value: " + m.group(0));
        } else {
            System.out.println("FALSE");
        }
    }

}

Result:

String "~!@#$%^&*(()_+<>?:"{}|\][;'./-=`" results to FALSE
String "~~1_~" results to TRUE  
String "~~k_~" results to TRUE -> Found value: k
String "~~汉_~" results to TRUE -> Found value: 汉

Upvotes: 1

Related Questions