原文: What Does $ Mean in RegEx? Dollar Metacharacter in Regular Expressions

$ 符号是正则表达式中最常用的符号之一。它用于匹配一个字符串的结尾。换句话说,你可以称它为“行尾锚”,因为它将一个模式锚定在行的末端。

在这篇文章中,我将向你展示美元符号($)在正则表达式中的确切作用以及如何使用它。

我们将讨论的内容

  • 正则表达式中的 $ 符号是什么
  • 如何匹配正则表达式中的美元符号 $
  • 如何在 JavaScript 正则表达式中使用美元符号 $
  • 总结

正则表达式中的 $ 符号是什么

$ 是 RegEx 中被称为元字符的字符之一。它与一个字符串的结尾相匹配,只有当它所连接的文本或字符串处于一行的结尾时,才会返回匹配。

这在你想确保一个字符串以某种模式或字符结束的情况下很有用。你可以将 $ 元字符与其他元字符一起使用,创建复杂的模式,以匹配特定的字符串或字符串中的模式。

在下面的例子中,你可以看到模式是 freecodecamp$igm 标志。i 表示不区分大小写,g 表示全局,m 表示多行。

Screenshot-2023-04-19-at-10.46.29

你还可以看到,只有行尾的 freeCoceCamp 这个词被返回匹配。这就是 $ 元字符的力量。

如何匹配正则表达式中的美元符号 $

美元符号 $ 是一个元字符,你如何在一个字符串中匹配它?你必须用反斜杠来转义它!这就是你在 RegEx 中匹配所有元字符的方法。

Screenshot-2023-04-19-at-10.46.37

如何在 JavaScript 正则表达式中使用美元符号 $

美元符号 $ 元字符在 JavaScript 中很有用。在下面的代码片段中,我将美元符号作为元字符和字符串进行测试:

const text1 =
  "At freeCodeCamp, we don't ask you to pay to learn coding, because freeCodeCamp is a charity";

const text2 =
  'You can also hang out with friends on a forum developed by freeCodeCamp';

const text3 = 'The sign of the naira is ₦ and dollar sign is $.';

const regex1 = /freecodecamp$/gim;
const regex2 = /\$/g;

// 测试美元符号作为元字符
console.log(regex1.test(text1)); //false
console.log(regex2.test(text2)); //true

// 测试美元符号作为字符串
console.log(regex2.test(text3)); //true

你可以看到,当我用正则表达式 /freecodecamp$/gim; 测试字符串 At freeCodeCamp, we don't ask you to pay to learn coding, because freeCodeCamp is a charity 时,它返回 false,因为在行尾没有 freeCodeCamp。但是当我用同样的正则测试 You can also hang out with friends on a forum developed by freeCodeCamp' 时,它返回了 true,因为在一行的末尾有一个 freeCodeCamp

另外,你可以看到,当我用正则 /\$/g 测试它时,字符串 'The sign of the naira is ₦ and dollar sign is $.' 返回 true

你也可以使用 exec() 方法代替 test() 来查看你的正则的精确匹配:

const text1 =
  "At freeCodeCamp, we don't ask you to pay to learn coding, because freeCodeCamp is a charity";

const text2 =
  'You can also hang out with friends on a forum developed by freeCodeCamp';

const text3 = 'The sign of the naira is ₦ and dollar sign is $.';

const regex1 = /freecodecamp$/gim;
const regex2 = /\$/g;

// 测试美元符号作为元字符
console.log(regex1.exec(text1));
console.log(regex1.exec(text2));

// 测试美元符号作为字符串
console.log(regex2.exec(text3));

输出:

null
[
  'freeCodeCamp',
  index: 59,
  input: 'You can also hang out with friends on a forum developed by freeCodeCamp',
  groups: undefined
]
[
  '$',
  index: 46,
  input: 'The sign of the naira is ₦ and dollar sign is $.',
  groups: undefined
]

第一个控制台日志返回 null,因为没有匹配。第二条返回了匹配信息,第三条也返回了匹配信息。

总结

你了解了美元($)元字符是如何在正则表达式和 JavaScript 中匹配行尾的。

你可以将美元元字符与其他几个元字符结合起来,创建一个复杂的模式。例如,脱字符(^)匹配一行的开始,你可以把它和美元元字符结合起来,只匹配一个特定的单词。

Happy coding!