Apply multiple regex patterns on a input and combine the end results

Viewed 73

I have a string where I need partial data that is located various (start) indexes using regex.

Input String

Hello, This community is here to help you with specific coding, algorithm, or language problems.

Expected Result

community is with specific language problems

I have individual regex patterns to grab the info I need. But I don't know how to combine together so that I can achieve my expected result. I could use a loop and then append the previous results through my code. Before that I wanted to see is there a solution so that I can avoid loop.

(?<=This).*(?=here)
(?<=you).*(?=coding)
(?<= or).*
2 Answers

You may use

/.*?\bThis\b\s*(.*)\bhere\b.*?\byou\b\s*(.*?)\bcoding\b.*?\bor\b\s*(.*)/

See the regex demo.

Details

  • .*? - any 0+ chars other than line break chars, as few as possible
  • \bThis\b - a whole word This
  • \s* - 0 or more whitespaces
  • (.*?) - Group 1: any 0+ chars other than line break chars, as few as possible
  • \bhere\b - whole word here
  • .*? - any 0+ chars other than line break chars, as few as possible
  • \byou\b - whole word you
  • \s* - 0 or more whitespaces
  • (.*?) - Group 2: any 0+ chars other than line break chars, as few as possible
  • \bcoding\b - whole word coding
  • .*? - any 0+ chars other than line break chars, as few as possible
  • \bor\b - whole word or
  • \s* - 0 or more whitespaces
  • (.*) - Group 3: any 0+ chars other than line break chars, as many as possible

See JavaScript demo:

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, "$1$2$3"));

Here is a combined version of the regex you have given in the explanation.

.*(?<=This)\s(.*)(?=here).*(?<=you)\s(.*)(?=coding).*(?<= or)\s(.*)

You can now combine group $1 $2 and $3 to get the desired result.

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,"$1$2$3"));

Related