简体   繁体   English

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

[英]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. 我想要这样一种验证,即我的字符串必须至少包含一个Unicode字母。 The character that will evaluate Character.isLetter() to true. 将Character.isLetter()评估为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. 我知道我可以使用Character.isLetter()进行for循环,但是我只是不想这样做。

And This is totally different from this since it only checks for the English alphabets, but in my case is about one unicode letter. 这是完全不同于 ,因为它只检查的英文字母,但对我来说是一个左右信Unicode的。 It's not a same at all. 根本不一样。

You can try to use this regex "\\\\p{L}|[0-9]" 您可以尝试使用此正则表达式"\\\\p{L}|[0-9]"

To better understand Unicode in Regex read this . 为了更好地了解Regex中的Unicode,请阅读此内容

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: 汉

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM