返回介绍

Summary

发布于 2025-02-27 23:45:45 字数 3062 浏览 0 评论 0 收藏 0

Regular expressions are objects that represent patterns in strings. They use their own syntax to express these patterns.

/abc/A sequence of characters
/[abc]/Any character from a set of characters
/[^abc]/Any character not in a set of characters
/[0-9]/Any character in a range of characters
/x+/One or more occurrences of the pattern x
/x+?/One or more occurrences, nongreedy
/x*/Zero or more occurrences
/x?/Zero or one occurrence
/x{2,4}/Between two and four occurrences
/(abc)/A group
/a|b|c/Any one of several patterns
/\d/Any digit character
/\w/An alphanumeric character (“word character”)
/\s/Any whitespace character
/./Any character except newlines
/\b/A word boundary
/^/Start of input
/$/End of input

A regular expression has a method test to test whether a given string matches it. It also has an exec method that, when a match is found, returns an array containing all matched groups. Such an array has an index property that indicates where the match started.

Strings have a match method to match them against a regular expression and a search method to search for one, returning only the starting position of the match. Their replace method can replace matches of a pattern with a replacement string. Alternatively, you can pass a function to replace , which will be used to build up a replacement string based on the match text and matched groups.

Regular expressions can have options, which are written after the closing slash. The i option makes the match case insensitive, while the g option makes the expression global, which, among other things, causes the replace method to replace all instances instead of just the first.

The RegExp constructor can be used to create a regular expression value from a string.

Regular expressions are a sharp tool with an awkward handle. They simplify some tasks tremendously but can quickly become unmanageable when applied to complex problems. Part of knowing how to use them is resisting the urge to try to shoehorn things that they cannot sanely express into them.

This is a book about getting computers to do what you want them to do. Computers are about as common as screwdrivers today, but they contain a lot more hidden complexity and thus are harder to operate and understand. To many, they remain alien, slightly threatening things.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文