CSS 标识符的允许字符 [英] Allowed characters for CSS identifiers
问题描述
CSS 标识符 id
和 class
的(完整)有效/允许的 charset 字符是什么?
What are the (full) valid / allowed charset characters for CSS identifiers id
and class
?
是否有可以用来验证的正则表达式?它与浏览器无关吗?
Is there a regular expression that I can use to validate against? Is it browser agnostic?
推荐答案
字符集无关紧要.允许的字符更重要.检查 CSS 规范.这是一个相关的引用:
The charset doesn't matter. The allowed characters matters more. Check the CSS specification. Here's a cite of relevance:
在 CSS 中,标识符(包括 选择器) 只能包含字符 [a-zA-Z0-9]
和 ISO 10646 字符 U+00A0
及更高,加上连字符 (-
) 和下划线 (_
);它们不能以一个数字、两个连字符或一个连字符后跟一个数字开头.标识符还可以包含转义字符和任何 ISO 10646 字符作为数字代码(参见下一项).例如,标识符 "B&W?"
可以写成 "B&W?"
或 "B26 W3F"
.
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters
[a-zA-Z0-9]
and ISO 10646 charactersU+00A0
and higher, plus the hyphen (-
) and the underscore (_
); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier"B&W?"
may be written as"B&W?"
or"B26 W3F"
.
更新:关于正则表达式的问题,你可以找到语法此处:
Update: As to the regex question, you can find the grammar here:
ident -?{nmstart}{nmchar}*
其中包含的部分:
nmstart [_a-z]|{nonascii}|{escape}
nmchar [_a-z0-9-]|{nonascii}|{escape}
nonascii [240-377]
escape {unicode}|\[^
f0-9a-f]
unicode \{h}{1,6}(
|[
f])?
h [0-9a-f]
这可以转换为 Java 正则表达式如下(我只在包含 OR 的部分添加了括号并转义了反斜杠):
This can be translated to a Java regex as follows (I only added parentheses to parts containing the OR and escaped the backslashes):
String h = "[0-9a-f]";
String unicode = "\\{h}{1,6}(\r\n|[ \t\r\n\f])?".replace("{h}", h);
String escape = "({unicode}|\\[^\r\n\f0-9a-f])".replace("{unicode}", unicode);
String nonascii = "[\240-\377]";
String nmchar = "([_a-z0-9-]|{nonascii}|{escape})".replace("{nonascii}", nonascii).replace("{escape}", escape);
String nmstart = "([_a-z]|{nonascii}|{escape})".replace("{nonascii}", nonascii).replace("{escape}", escape);
String ident = "-?{nmstart}{nmchar}*".replace("{nmstart}", nmstart).replace("{nmchar}", nmchar);
System.out.println(ident); // The full regex.
更新 2:哦,您更像是一个 PHP 爱好者,我想您可以弄清楚如何/在哪里做 str_replace
?
Update 2: oh, you're more a PHP'er, well I think you can figure how/where to do str_replace
?
这篇关于CSS 标识符的允许字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!