【发布时间】:2011-09-13 10:53:48
【问题描述】:
这里有一个关于CamelCase regex 的问题。结合tchrist post,我想知道正确的 utf-8 CamelCase 是什么。
从 (brian d foy's) 正则表达式开始:
/
\b # start at word boundary
[A-Z] # start with upper
[a-zA-Z]* # followed by any alpha
(?: # non-capturing grouping for alternation precedence
[a-z][a-zA-Z]*[A-Z] # next bit is lower, any zero or more, ending with upper
| # or
[A-Z][a-zA-Z]*[a-z] # next bit is upper, any zero or more, ending with lower
)
[a-zA-Z]* # anything that's left
\b # end at word
/x
并修改为:
/
\b # start at word boundary
\p{Uppercase_Letter} # start with upper
\p{Alphabetic}* # followed by any alpha
(?: # non-capturing grouping for alternation precedence
\p{Lowercase_Letter}[a-zA-Z]*\p{Uppercase_Letter} ### next bit is lower, any zero or more, ending with upper
| # or
\p{Uppercase_Letter}[a-zA-Z]*\p{Lowercase_Letter} ### next bit is upper, any zero or more, ending with lower
)
\p{Alphabetic}* # anything that's left
\b # end at word
/x
标记为“###”的行有问题。
另外,假设数字和下划线等价于小写字母时如何修改正则表达式,所以W2X3是一个有效的CamelCase单词。
更新:(ysth 评论)
接下来,
-
any:意思是“大写或小写或数字或下划线”
正则表达式应该匹配 CamelWord, CaW
- 以大写字母开头
- 可选任何
- 小写字母或数字或下划线
- 可选任何
- 大写字母
- 可选任何
请不要标记为重复,因为它不是。 original question(以及答案)只考虑 ascii。
【问题讨论】:
-
那是你开始使用的一个非常奇怪的正则表达式;我认为它与更简单的
/\b[A-Z]+[a-z][A-Za-z]*\b/(仅由字母组成的“单词”,以大写字母开头并包括至少一个小写字母)匹配没有任何不同(更新:我错了,原来的正则表达式至少需要三个字母。) -
无论如何,请不要以 ASCII 正则表达式开头;尽可能精确地定义您想要匹配的内容
-
更新了问题——用(我希望足够)精确的定义
-
Nit:当您指的是 Unicode 时,您会说 UTF-8。 UTF-8 是一种将文本存储为字节的方式,但您的正则表达式显然适用于文本。
-
那不是我的正则表达式。 j_random_hacker came up with that,虽然我后来用 /x 开关修改了它。
标签: regex perl unicode utf-8 camelcasing