簡體   English   中英

使用正則表達式檢查一個字符串至少包含一個Unicode字母

[英]Check a string contains at least one Unicode letter using regex

我想要這樣一種驗證,即我的字符串必須至少包含一個Unicode字母。 將Character.isLetter()評估為true的字符。

例如我想要

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

我知道我可以使用Character.isLetter()進行for循環,但是我只是不想這樣做。

這是完全不同於 ,因為它只檢查的英文字母,但對我來說是一個左右信Unicode的。 根本不一樣。

您可以嘗試使用此正則表達式"\\\\p{L}|[0-9]"

為了更好地了解Regex中的Unicode,請閱讀此內容

使用代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM