在字符类中如何解释单词字符? [英] How word character is interpreted in character class?

查看:112
本文介绍了在字符类中如何解释单词字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

\w-表示[A-Za-z0-9_] > 字符类

\w - stands for [A-Za-z0-9_] Character class

但是我无法理解它在字符类中是如何解释的.

But i am not able to understand how it is interpreted inside character class.

所以当我使用

[\w-~]

let test = (str) => /^[\w-~]+$/.test(str)

console.log(test("T|"))

对于T|

但是当我使用

[A-Za-z0-9_-~]

let test = (str) => /^[A-Za-z0-9_-~]+$/.test(str)

console.log(test("T|"))

结果为真

我无法理解这两个表达式有何不同?

i am not able to understand how these two expressions are different from each other ?

推荐答案

我相信,两个示例之间的主要区别在于-字符的位置.在此示例中发生的事情是

I believe that the main difference between both your examples is the location of your - character. What's happening here is that in this example:

let test = (str) => /^[A-Za-z0-9_-~]+$/.test(str)

console.log(test("T|"))

它被评估为范围,如下所示:

It's evaluated as a range, like so:

let test = (str) => /^[_-~]+$/.test(str)

console.log(test("|"))

将返回 true .

在此位置:

let test = (str) => /^[\w-~]+$/.test(str)

console.log(test("T|"))

由于 \ w 本身就是一组字符,因此它会自行评估字符-.

Since \w is a set of characters in and of itself, it's evaluating the character - by itself.

-及其周围的位置可能会在解释方式上产生巨大差异.

The position of - and it's surrounding can make a huge difference in how it's interpreted.

您可以通过将其移至末尾来完全避免这种情况,如下所示:

You could avoid that situation, altogether, by moving it to the end, like so:

let test = (str) => /^[A-Za-z0-9_~-]+$/.test(str)

console.log(test("T|"))

将返回 false

这篇关于在字符类中如何解释单词字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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