PHP 果然是最好的语言之正则的兼容问题。

2016-03-09 12:04:40 +08:00
 ChoateYao

测试一个匹配字母和数字的正则:

pattern='/^\w+$/'
string='人 1994'

PHP 结果

Array
(
    [0] => 人 1994
)

Javascript 结果

匹配不到数据

结论
PHP 是世界上最好的语言,我在这个细节上浪费了 30 分钟。

如果要匹配字母和数字最好使用以下方法:

/^[a-zA-Z\d_]+$/
3656 次点击
所在节点    PHP
29 条回复
eoo
2016-03-09 14:40:19 +08:00
@Jaylee 你这个没啥问题啊
jfcherng
2016-03-09 15:52:07 +08:00
/^\w+$/u 匹配成功!?
https://3v4l.org/mklML
kungfuchicken
2016-03-09 17:27:53 +08:00
我在 Mac 上测试 PHP ( mac port 安装)是可以匹配到“人”的,但是在 Cent OS 上测试了几个版本的 PHP (编译安装和 yum 安装都有,跟 Mac 版本相同)都是匹配不到的

这个不是 PHP 的锅,而是 PCRE 库的配置导致,\w 的匹配官方文档是这么说的

A "word" character is any letter or digit or the underscore character, that is, any character which can be part of a Perl "word". The definition of letters and digits is controlled by PCRE's character tables, and may vary if locale-specific matching is taking place. For example, in the "fr" (French) locale, some character codes greater than 128 are used for accented letters, and these are matched by \w.

也就是说, PCRE 库的 character tables 配置会影响到\w 的匹配
yaxin
2016-03-09 18:38:39 +08:00
@Strikeactor 什么编辑器,这么好
Strikeactor
2016-03-09 18:51:51 +08:00
yaxin
2016-03-09 19:10:26 +08:00
@Strikeactor 谢谢,不错的编辑器,而且也不贵
ming2281
2016-03-09 19:44:44 +08:00
js 支持的正则元素不完整(指流行的 Perl 风格)
flynaj
2016-03-10 14:15:37 +08:00
EmEditor \w 可以匹配中文,
使用 Boost library Regex++ 的正则表达式惯例
https://zh-cn.emeditor.com/help/howto/search/search_regexp_syntax.htm
yumijie
2016-03-10 15:04:17 +08:00
编码的问题好像楼主没考虑

22 楼的网友考虑了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/262150

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX