BeingDev
BeingDev

Reputation: 426

JavaScript: Regex to get string between ";;;"

I have seen couple similar post related my question, but I'm unable to get my Regex right.

how to get string in between ";;;" as shown below

;;; My Result ;;; --> My Result
;;; Title:Learning Regex ;;; --> Title:Learning Regex
;;; with all special characters !@#$%^&*()';" ;;; --> with all special characters !@#$%^&*()';"
;;; this should return nothing --> ""

tried below solution but no luck

 var str = ';;; Title:Learning Regex ;;;';
 var res= str.match(/^;{3}\w;{3}$/).pop();

any JavaScript Regex Guru, please help.

Upvotes: 1

Views: 69

Answers (2)

mcon
mcon

Reputation: 664

If you're interested, here's a solution using split.

var str = ";;; My Result ;;; --> My Result;;; Title:Learning Regex ;;; --> Title:Learning Regex;;; with all special characters !@#$%^&*()';\" ;;; --> with all special characters !@#$%^&*()';\";;; this should return nothing --> \"\"";

var res = str.split(";;;");

res.forEach(function(value){
	console.log(value);
});

One thing to note is that there's a blank index at the beginning because it splits on the first ;;; and you get {'', My Result, ... }.

Split may not help in this instance for this exact reason, but it might not be too difficult for you to use strings like My Result ;;; --> My Result;;; Title:Learning Regex ;;; --> Title:Learning Regex;;; with all special characters !@#$%^&*()';\" ;;; --> with all special characters !@#$%^&*()';\";;; this should return nothing --> \"\" instead. Just be careful of excess white space if you use something like this.

Also, in my opinion, a solution using split is better suited in this case since you know exactly what your string delimiters are. Not sure how it stands up performance wise.

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627419

The biggest problem with this task is that you might want to differentiate between non-three semi-colon delimiters.

I'd suggest

^;{3}(?!;)([\s\S]*?[^;]);{3}$

For standalone strings use a version with greedy quantifier:

^;{3}(?!;)([\s\S]*[^;]);{3}$
                 ^

See demo

Explanation:

  • ^ - start of string
  • ;{3} - 3 semi-colons
  • (?!;) - fail a match if the next character is a ;
  • ([\s\S]*?[^;]) - match zero or more characters (incl. a newline) up to the last 3 semi-colons, and the 4th character from the end cannot be a ; (NOTE: when using with standalone strings, replace [\s\S]*? with [\s\S]*,a greedy version!)
  • ;{3} - 3 semi-colons
  • $ - end of string

Upvotes: 2

Related Questions