在输入上应用多个正则表达式模式并组合最终结果
Apply multiple regex patterns on a input and combine the end results
我有一个字符串,我需要使用正则表达式位于各种(开始)索引中的部分数据。
输入字符串
Hello, This community is here to help you with specific coding, algorithm, or language problems.
预期结果
community is with specific language problems
我有单独的正则表达式模式来获取我需要的信息。但是我不知道如何组合在一起才能达到预期的结果。我可以使用一个循环,然后通过我的代码附加以前的结果。在那之前我想看看有没有解决方案,这样我就可以避免循环。
(?<=This).*(?=here)
(?<=you).*(?=coding)
(?<= or).*
您可以使用
/.*?\bThis\b\s*(.*)\bhere\b.*?\byou\b\s*(.*?)\bcoding\b.*?\bor\b\s*(.*)/
参见regex demo。
详情
.*?
- 除换行字符外的任何 0+ 个字符,尽可能少
\bThis\b
- 一个完整的单词 This
\s*
- 0 个或更多空格
(.*?)
- 第 1 组:除换行字符外的任何 0+ 个字符,尽可能少
\bhere\b
- 整个单词 here
.*?
- 除换行字符外的任何 0+ 个字符,尽可能少
\byou\b
- 整个单词 you
\s*
- 0 个或更多空格
(.*?)
- 第 2 组:除换行字符外的任何 0+ 个字符,尽可能少
\bcoding\b
- 整个单词 coding
.*?
- 除换行字符外的任何 0+ 个字符,尽可能少
\bor\b
- 整个单词 or
\s*
- 0 个或更多空格
(.*)
- 第 3 组:除换行字符外的任何 0+ 个字符,尽可能多
参见JavaScript演示:
const regex = /.*?\bThis\b\s*(.*?)\bhere\b.*?\byou\b\s*(.*?)\bcoding\b.*?\bor\b\s*(.*)/;
const str = "Hello, This community is here to help you with specific coding, algorithm, or language problems.";
console.log(str.replace(regex, ""));
这是您在解释中给出的正则表达式的组合版本。
.*(?<=This)\s(.*)(?=here).*(?<=you)\s(.*)(?=coding).*(?<= or)\s(.*)
您现在可以组合组 $1 $2 和 $3 以获得所需的结果。
let inpStr = "Hello, This community is here to help you with specific coding, algorithm, or language problems.";
let regex = /.*(?<=This)\s(.*)(?=here).*(?<=you)\s(.*)(?=coding).*(?<= or)\s(.*)/;
console.log(inpStr.replace(regex,""));
我有一个字符串,我需要使用正则表达式位于各种(开始)索引中的部分数据。
输入字符串
Hello, This community is here to help you with specific coding, algorithm, or language problems.
预期结果
community is with specific language problems
我有单独的正则表达式模式来获取我需要的信息。但是我不知道如何组合在一起才能达到预期的结果。我可以使用一个循环,然后通过我的代码附加以前的结果。在那之前我想看看有没有解决方案,这样我就可以避免循环。
(?<=This).*(?=here)
(?<=you).*(?=coding)
(?<= or).*
您可以使用
/.*?\bThis\b\s*(.*)\bhere\b.*?\byou\b\s*(.*?)\bcoding\b.*?\bor\b\s*(.*)/
参见regex demo。
详情
.*?
- 除换行字符外的任何 0+ 个字符,尽可能少\bThis\b
- 一个完整的单词This
\s*
- 0 个或更多空格(.*?)
- 第 1 组:除换行字符外的任何 0+ 个字符,尽可能少\bhere\b
- 整个单词here
.*?
- 除换行字符外的任何 0+ 个字符,尽可能少\byou\b
- 整个单词you
\s*
- 0 个或更多空格(.*?)
- 第 2 组:除换行字符外的任何 0+ 个字符,尽可能少\bcoding\b
- 整个单词coding
.*?
- 除换行字符外的任何 0+ 个字符,尽可能少\bor\b
- 整个单词or
\s*
- 0 个或更多空格(.*)
- 第 3 组:除换行字符外的任何 0+ 个字符,尽可能多
参见JavaScript演示:
const regex = /.*?\bThis\b\s*(.*?)\bhere\b.*?\byou\b\s*(.*?)\bcoding\b.*?\bor\b\s*(.*)/;
const str = "Hello, This community is here to help you with specific coding, algorithm, or language problems.";
console.log(str.replace(regex, ""));
这是您在解释中给出的正则表达式的组合版本。
.*(?<=This)\s(.*)(?=here).*(?<=you)\s(.*)(?=coding).*(?<= or)\s(.*)
您现在可以组合组 $1 $2 和 $3 以获得所需的结果。
let inpStr = "Hello, This community is here to help you with specific coding, algorithm, or language problems.";
let regex = /.*(?<=This)\s(.*)(?=here).*(?<=you)\s(.*)(?=coding).*(?<= or)\s(.*)/;
console.log(inpStr.replace(regex,""));