正则表达式风格

特性对比

特性PCRE/PHPPython reJavaScript
命名分组(?P<n>...)(?P<n>...)(?<n>...)
后行断言(?<=...)(?<=...)ES2018+
递归模式(?R)NoNo
Unicode 属性\p{L}regex pkg\p{L} ES2018
原子组(?>...)NoNo
占有量词*+, ++NoNo
内联标志(?i)(?i)No
点号匹配换行(?s) or /sre.DOTALL/s ES2018

命名分组

语言语法访问方式
PCRE / PHP(?P<year>\d{4})$matches['year']
Python(?P<year>\d{4})m.group('year')
JavaScript(?<year>\d{4})m.groups.year
Go(?P<year>\d{4})m[re.SubexpIndex("year")]

常用模式

用途Regex
电子邮件^[^\s@]+@[^\s@]+\.[^\s@]+$
网址https?://[^\s/$.?#].[^\s]*
IPv4地址(\d{1,3}\.){3}\d{1,3}
日期\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])
十六进制颜色#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})
UUID[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}