Javascript 分隔符和换行符之间的字符串的适当正则表达式是什么

Javascript 分隔符和换行符之间的字符串的适当正则表达式是什么,javascript,regex,Javascript,Regex,使用换行符捕获中间分隔符中的字符串的正则表达式是什么 字符串为: /* start \*/This is a test of regex 带有新行和(特殊字符) 请建议输出:-***这是对正则表达式的测试 带有新行和(特殊字符) i、 介于/*开始*/和/*结束*/之间的字符串 Here **/* start */** and **/\* end */** are the **delimiters**. 您可以使用[^]*? 例如: var string=`/*start*/这是对正则表达

使用换行符捕获中间分隔符中的字符串的正则表达式是什么

字符串为:

/* start \*/This is a test of regex
带有新行和(特殊字符)

请建议输出:-***这是对正则表达式的测试 带有新行和(特殊字符)

i、 介于/*开始*/和/*结束*/之间的字符串

Here **/* start */** and **/\* end */** are the **delimiters**.

您可以使用
[^]*?

例如:

var string=`/*start*/这是对正则表达式的测试
带有新行和(特殊字符)
asdsadasd/*end*/`;
var result=string.match(/\/\*\start\*\/([^]*?)\/\*end\*/);

console.log(结果[1])您可以使用
[^]*?

例如:

var string=`/*start*/这是对正则表达式的测试
带有新行和(特殊字符)
asdsadasd/*end*/`;
var result=string.match(/\/\*\start\*\/([^]*?)\/\*end\*/);

console.log(结果[1])此正则表达式将匹配您所追求的内容:
/\/\*开始\*\/(.*?\/\*结束\*\//gs

  • \
    *
    需要转义,因为它们是正则表达式中的特殊字符
  • (.*)
    部分告诉它捕获包含任何字符的最短匹配
  • 末尾的
    gs
    告诉它支持多个匹配(
    g
    ),并且
    应该匹配新行字符(
    s
示例代码:

const regex = /\/\* start \*\/(.*?)\/\* end \*\//gs;
const str = `/* start */This is a test of regex

with new line and (special char)

asdsadasd/* end */
assorted unmatched crap

/* start */another match/* end */

blah blah blah

/* start */another
multi
line
match
/* end */
`;

let match;
while ((match = regex.exec(str)) !== null) {
    console.log(`Found a match: ${match[0]}`);
    console.log('----------------------------------');
}

此正则表达式将匹配您所追求的内容:
/\/\*开始\*\/(.*?\/\*结束\*\//gs

  • \
    *
    需要转义,因为它们是正则表达式中的特殊字符
  • (.*)
    部分告诉它捕获包含任何字符的最短匹配
  • 末尾的
    gs
    告诉它支持多个匹配(
    g
    ),并且
    应该匹配新行字符(
    s
示例代码:

const regex = /\/\* start \*\/(.*?)\/\* end \*\//gs;
const str = `/* start */This is a test of regex

with new line and (special char)

asdsadasd/* end */
assorted unmatched crap

/* start */another match/* end */

blah blah blah

/* start */another
multi
line
match
/* end */
`;

let match;
while ((match = regex.exec(str)) !== null) {
    console.log(`Found a match: ${match[0]}`);
    console.log('----------------------------------');
}

什么是/s和g的意思。g是全局匹配,但什么是“s”,因为我没有清楚地理解。文档上说是单行。点匹配换行符。你能澄清一下吗?它的意思就是这样!默认情况下,
将与新行不匹配。如果从上面的示例中删除
s
,您会注意到它将只匹配第二个结果(即没有换行符的结果),因为
(.+?)
部分不再匹配新行。我还忘了提到
match[0]
显示了完整的匹配文本,您可以使用
match[1]
来获取您真正感兴趣的部分,即/s和g的含义。g是全局匹配,但“s”是什么,因为我没有清楚地理解。文档中说是单行。点匹配换行符。你能澄清一下吗?它的意思就是这样!默认情况下,
将与新行不匹配。如果从上面的示例中删除
s
,您会注意到它将只匹配第二个结果(即没有换行符的结果),因为
(.+?)
部分不再匹配新行。我还忘了提到
match[0]
显示了完整的匹配文本,您可以使用
match[1]
来获取您真正感兴趣的零件
const regex = /\/\* start \*\/(.*?)\/\* end \*\//gs;
const str = `/* start */This is a test of regex

with new line and (special char)

asdsadasd/* end */
assorted unmatched crap

/* start */another match/* end */

blah blah blah

/* start */another
multi
line
match
/* end */
`;

let match;
while ((match = regex.exec(str)) !== null) {
    console.log(`Found a match: ${match[0]}`);
    console.log('----------------------------------');
}