通配符:.
通配符匹配除行终止符外的所有字符。如果设置了 s 标志,它也会匹配行终止符。
语法
正则表达式
.
描述
. 匹配除行终止符外的任何字符。如果设置了s 标志,. 也会匹配行终止符。
. 匹配的具体字符集取决于正则表达式是否支持 Unicode。如果支持 Unicode,. 匹配任何 Unicode 码点;否则,它匹配任何 UTF-16 码元。例如
js
/../.test("😄"); // true; matches two UTF-16 code units as a surrogate pair
/../u.test("😄"); // false; input only has one Unicode character
示例
与量词一起使用
通配符通常与量词一起使用,以匹配任何字符序列,直到找到下一个感兴趣的字符。例如,以下示例提取 Markdown 页面中形如 # 标题 的标题
js
function parseTitle(entry) {
// Use multiline mode because the title may not be at the start of
// the file. Note that the m flag does not make . match line
// terminators, so the title must be on a single line
// Return text matched by the first capturing group.
return /^#[ \t]+(.+)$/m.exec(entry)?.[1];
}
parseTitle("# Hello world"); // "Hello world"
parseTitle("## Subsection"); // undefined
parseTitle(`
---
slug: Web/JavaScript/Reference/Regular_expressions/Wildcard
---
# Wildcard: .
A **wildcard** matches all characters except line terminators.
`); // "Wildcard: ."
匹配代码块内容
以下示例匹配 Markdown 中由三个反引号括起来的代码块内容。它使用 s 标志使 . 匹配行终止符,因为代码块的内容可能跨多行
js
function parseCodeBlock(entry) {
return /^```.*?^(.+?)\n```/ms.exec(entry)?.[1];
}
parseCodeBlock(`
\`\`\`js
console.log("Hello world");
\`\`\`
`); // "console.log("Hello world");"
parseCodeBlock(`
A \`try...catch\` statement must have the blocks enclosed in curly braces.
\`\`\`js example-bad
try
doSomething();
catch (e)
console.log(e);
\`\`\`
`); // "try\n doSomething();\ncatch (e)\n console.log(e);"
警告:这些示例仅用于演示。如果您想解析 Markdown,请使用专门的 Markdown 解析器,因为有许多边界情况需要考虑。
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # prod-Atom |
浏览器兼容性
加载中…