我需要确保电子邮件地址包含标准美国英语字符。在不讨论这意味着什么以及是否可取的情况下,我想知道仅正则表达式是否足以满足该要求,或者我还需要检查字符集吗?
是否存在可以将 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
方法在技术上不能保证有效。您使用的 getBytes
方法和 String
构造函数都是 documented当给定字符/字节作为指定字符编码的一部分无效时,具有未指定的行为。
关于java - 正则表达式是否足够,或者我需要检查编码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25548466/