簡體   English   中英

Regex是否足夠,還是需要檢查編碼?

[英]Is Regex Sufficient, or Do I need to check Encoding?

我要求確保電子郵件地址包含標准的美國英語字符。 在不討論這意味着什么以及是否建議的情況下,我想知道僅一個正則表達式是否足以滿足該要求,還是我還需要檢查字符集?

是否在任何情況下都可以將UTF-8字符傳遞給正則表達式,但不能傳遞給該正則表達式中使用的拉丁字符集?

這是我正在使用的一些代碼,在我看來正則表達式已足夠,但我需要第二種意見。

package misc;

import java.io.UnsupportedEncodingException;

public class ValidateCharacterSet {
    public static void main(String args[]) {
        String czech = "Český";
        String japanese = "日本語";
        String spanish = "¡Qué magnifico es java!";
        String english = "elephant_in-theRoom@yahoo.com";

        System.out.println("iso check: " + czech + ":" + isISO8859(czech));
        System.out.println("iso check: " + japanese + ":" + isISO8859(japanese));
        System.out.println("iso check: " + spanish + ":" + isISO8859(spanish));
        System.out.println("iso check: " + english + ":" + isISO8859(english));

        System.out.println("");

        System.out.println("regex match: " + czech + ":" + playWithMatches(czech));
        System.out.println("regex match: " + japanese + ":" + playWithMatches(japanese));
        System.out.println("regex match: " + spanish + ":" + playWithMatches(spanish));
        System.out.println("regex match: " + english + ":" + playWithMatches(english));
    }


    /**
     * Returns true if the string is null, or the original string (str) equals the string (encodedAsISO8859)
     * that was encoded ISO-8859-1.
     *
     * @param str String containing bytes for which to check the encoding.
     * @return True if the string is in ISO-8859-1 format.
     */
    private static boolean isISO8859(String str) {
        // a null string is compliant by definition.
        if (str == null) {
            return true;
        }

        try {
            byte[] iso88591Data = str.getBytes("ISO-8859-1");
            String encodedAsISO8859 = new String(iso88591Data, "ISO-8859-1");
            if (str.equals(encodedAsISO8859)) {
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return false;
    }

    private static boolean playWithMatches(String str) {
        return (str != null && str.matches("[A-Za-z0-9\\-_\\.@\\+]+"));
    }
}

我認為您正在混淆字符集字符編碼。 字符集是允許或可用的字符集,而字符編碼描述了如何訪問字符集。 對於像ISO-8859-1這樣的字符集,這種區別並不明顯,因為那里只有一個標准編碼,即傳遞數字可以使您獲得與該數字關聯的字符。 在處理像Unicode這樣的字符集時,這一點更加明顯,因為一個字符集有多種編碼,即UTF-8,UTF-16,UTF-32 (Java在其字符串中使用UTF-16)。

一旦定義了字符集(在本例中為“標准美國英語字符”),則正則表達式足以檢查給定字符串中的字符是否僅包含字符集中的那些字符。 您不需要,也不需要處理較低級別的編碼問題。 isISO8859來說,技術上不能保證您的isISO8859方法有效。 當給定的字符/字節作為指定字符編碼的一部分無效時,您使用的getBytes方法和String構造函數均被記錄為具有未指定的行為。

暫無
暫無

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

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