1

I have the following string:

%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%

PROBLEM: I am trying to match all occurrences between %||....||% and process those substring matches

MY REGEX: /%([\s\S]*?)(?=%)/g

MY CODE

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";

var pattern = /%([\s\S]*?)(?=%)/g;

a.replace( pattern, function replacer(match){
    return match.doSomething();
} );

Now the patterns seems to be selecting the everything between the first and last occurrence of %|| .... %||

MY FIDDLE

WHAT I NEED:

I want to iterate over the matches

%||1234567890||Joe||%

AND

%||1234567890||Robert||%

and do something

1
  • Try replacing the pattern with /%\|\|([\s\S]*?)(?=\|\|%)/g or even /%\|\|([\s\S]*?)\|\|%/g - regex101.com/r/ugkkNa/1. Then use the a = a.replace(/pattern/g, function ($0, $1) {return ...;}) Commented Mar 31, 2017 at 9:05

2 Answers 2

1

You need to use a callback inside a String#replace and modify the pattern to only match what is inside %|| and ||% like this:

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";
var pattern = /%\|\|([\s\S]*?)\|\|%/g;
a = a.replace( pattern, function (match, group1){
    var chunks = group1.split('||');
    return "{1}" + chunks.join("-") + "{/1}";
} );
console.log(a);

The /%\|\|([\s\S]*?)\|\|%/g pattern will match:

  • %\|\| - a %|| substring
  • ([\s\S]*?) - Capturing group 1 matching any 0+ chars as few as possible up to the first...
  • \|\|% - a ||% substring
  • /g - multiple times.
Sign up to request clarification or add additional context in comments.

1 Comment

Simply brilliant! Thank you Wiktor :)
0

Because he tries to take as much as possible, and [\s\S] basically means "anything". So he takes anything.

RegExp parts without escaping, exploded for readability
start tag : %||
first info: ([^|]*) // will stop at the first |
separator : ||
last info : ([^|]*) // will stop at the first |
end tag   : ||%

Escaped RegExp:
/%\|\|([^\|]*)\|\|([^\|]*)\|\|%/g

3 Comments

This regex won't match values like %||123456|7890||Joe||%
You're not supposed to use the delimiting character in the values. But from the exemples given, it won't happen.
From the examples given, the delimiter is a 2-char string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.