使用正则表达式检查一个字符串至少包含一个Unicode字母

时间:2019-03-05 02:15:13

标签: java regex

我想要这样一种验证,即“我的字符串”必须至少包含一个Unicode字母。将Character.isLetter()评估为true的字符。

例如我想要

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

我知道我可以在Character.isLetter()中使用for循环,但是我只是不想这样做。

这与this完全不同,因为它仅检查英文字母,但在我的情况下是一个Unicode字母。根本不一样。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用此正则表达式"\\p{L}|[0-9]"

要更好地了解Regex中的Unicode,请阅读this

使用代码:

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");
        }
    }

}

结果:

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