M4X_
M4X_

Reputation: 547

Javascript regex to match items enclosed by a pair of characters?

I want a regex to match everything between the characters (* and *). I also need (* and *) to be matched in the result as well.

For example;

Such a regex is applied to the code below;

(*
  * Something here
  * Many things can appear here
  * More things can appear here
  * Added another can appear here
*)

(*****************************************) Something here

Something here (*****************************************) 


(* Content can also exist here *) Something here

Something here (* Content can also exist here *) 


(Some content here ) (* Content can also exist here *) 

  * Something here
  * Many things can appear here
  * More things can appear here
  * Added another can appear here

The result only contains;

(*
  * Something here
  * Many things can appear here
  * More things can appear here
  * Added another can appear here
*)

(*****************************************) 

(*****************************************) 


(* Content can also exist here *) 

(* Content can also exist here *) 

(* Content can also exist here *) 

I had something going on https://regexr.com/4nset

([\(\*].*(?:\*\)))

but it seems to not be working as expected.

Upvotes: 3

Views: 164

Answers (3)

BCDeWitt
BCDeWitt

Reputation: 4773

/\(\*.*?\*\)/gs, where the s flag helps the dot symbol to match newline characters.

NOTE: This doesn't work cross-browser as of now. Other answers should be more suitable until it is properly supported.

const str = `(*
  * Something here
  * Many things can appear here
  * More things can appear here
  * Added another can appear here
*)

(*****************************************) Something here

Something here (*****************************************) 


(* Content can also exist here *) Something here

Something here (* Content can also exist here *) 


(Some content here ) (* Content can also exist here *) 

  * Something here
  * Many things can appear here
  * More things can appear here
  * Added another can appear here`

const re = /\(\*.*?\*\)/gs

console.log(
  str.match(re)
)

Upvotes: 2

guillaumepotier
guillaumepotier

Reputation: 7448

Try this one:

(\(\*[^\(]*(?:\*\)))/gmi

Here is a link to a Regex101 working demo: https://regex101.com/r/eB4a4U/2/

Upvotes: 1

anubhava
anubhava

Reputation: 785196

Assuming there are no nested or escaped brackets, you may use this regex in Javascript:

/\(\*[\s\S]*?\*\)/g

Updated RegEx Demo

RegEx Details:

  • \(\*: Match starting (*
  • [\s\S]*?: Match 0 or more of any characters including newlines (non-greedy)
  • \*\): Match closing *)

Upvotes: 3

Related Questions