regex 如何在带换行符的符号之间选择内容

x6492ojm  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(110)

我已经想了好几个小时了,还是想不出一个解决办法。
假设我们有下面的文本:

The `replace()` method is used to replace a substring or regular expression in a string with a new substring or function. The basic syntax for this method is as follows:

***
string.replace(searchValue, replaceValue)
***

Here, `string` is the original string where the replacement will take place, `searchValue` is the substring or regular expression that needs to be replaced, and `replaceValue` is the new substring that will replace the old one.

For example, if we have a string `var str = "Hello World"`, and we want to replace the word "World" with "JavaScript", we can use the `replace()` method as follows:

***javascript
var str = "Hello World";
var newStr = str.replace("World", "JavaScript");

console.log(newStr); // Output: "Hello JavaScript"
***

我想选择的是:

***
string.replace(searchValue, replaceValue)
***

以及:

***javascript
var str = "Hello World";
var newStr = str.replace("World", "JavaScript");

console.log(newStr); // Output: "Hello JavaScript"
***

我当前的Regex是***(.+?)?\n((?:.+\n)+?)***
让我解释一下,***(.+?)?,因为***后面的javascript是可选的,因为它可能不存在,也可能是其他单词,然后((?:.+\n)+?)表示一行中有一个或多个句子。(对不起,我需要捕获组)
如果没有换行符,则有效,如:

***javascript
var str = "Hello World";
var newStr = str.replace("World", "JavaScript");
console.log(newStr); // Output: "Hello JavaScript"
***

但是换行符是可选的,因为我不知道是否会有换行符,所以Regex需要工作,无论是没有换行符,还是有一个换行符或多个换行符…

  • 实际上是`因为在编辑器这里很难逃脱它。你可以试试here
hwamh0ep

hwamh0ep1#

在regexp上使用s标志允许.匹配换行符。
您还需要转义regexp中的*字符。

const text = `The \`replace()\` method is used to replace a substring or regular expression in a string with a new substring or function. The basic syntax for this method is as follows:

\`\`\`
string.replace(searchValue, replaceValue)
\`\`\`

Here, \`string\` is the original string where the replacement will take place, \`searchValue\` is the substring or regular expression that needs to be replaced, and \`replaceValue\` is the new substring that will replace the old one.

For example, if we have a string \`var str = "Hello World"\`, and we want to replace the word "World" with "JavaScript", we can use the \`replace()\` method as follows:

\`\`\`javascript
var str = "Hello World";
var newStr = str.replace("World", "JavaScript");

console.log(newStr); // Output: "Hello JavaScript"
\`\`\``;

matches = text.match(/```(.*?)\n(.+?)```/sg);

console.log(matches);

相关问题