[\s\S] 与 .(点)? [英] Is [\s\S] same as . (dot)?

查看:40
本文介绍了[\s\S] 与 .(点)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们在同一个字符类中包含字符类和否定字符类的速记时,它是否与点相同.表示任何字符?

我对

在这种情况下,如果您在 regex101 中看到

所以,总而言之,当您想匹配多行而 . 不适合您的需求时,[\s\S] 是一个正则表达式技巧.这基本上取决于您的用例.

但是,如果您在 . 匹配新行的地方使用 single line 标志,那么您不需要正则表达式技巧,下面您可以看到所有内容都是绿色的和第 2 组(上面红色)不匹配:

还创建了一个 javascript 性能测试,它对性能的影响约为 25%:

When we include shorthand for character class and negated-character class in same character class, is it same as dot . which mean any character ?

I did a test on regex101.com and every character matched.

Is [\s\S] [\w\W] and [\d\D] same as . ?

I want to know if this behavior is persistent in web's front and backend languages like Javascript, Php, Python and others.

解决方案

"No" it is not the same. It has an important difference if you are not using the single line flag (meaning that . does not match all).

The [\s\S] comes handy when you want to do mix of matches when the . does not match all.

It is easier to explain it with an example. Suppose you want to capture whatever is between a and b, so you can use pattern a(.*?)b (? is for ungreedy matches and parentheses for capturing the content), but if there are new lines suppose you don't want to capture this in the same group, so you can have another regex like a([\s\S]*?)b.

Therefore if we create one pattern using both approaches it results in:

a(.*)b|a([\s\S]*?)b

In this case, if you see the scenario in regex101, then you will have a colorful and easy way to differentiate the scenarios (in green capturing group #1 and in red capturing group #2):

So, in conclusion, the [\s\S] is a regex trick when you want to match multiple lines and the . does not suit your needs. It basically depends on your use case.

However, if you use the single line flag where . matches new lines, then you don't need the regex trick, below you can see that all is green and group 2 (red above) is not matched:

Have also created a javascript performance test and it impacts in the performance around 25%:

https://jsperf.com/ss-vs-dot

这篇关于[\s\S] 与 .(点)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆