首页 > 解决方案 > Javascript正则表达式匹配由一对字符包围的项目?

问题描述

我想要一个正则表达式来匹配字符(**). 我也需要(**)在结果中匹配。

例如;

这样的正则表达式适用于下面的代码;

(*
  * 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

结果只包含;

(*
  * 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 *) 

我有一些事情发生在https://regexr.com/4nset

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

但它似乎没有按预期工作。

标签: javascriptregex

解决方案


假设没有嵌套或转义括号,您可以在 Javascript 中使用此正则表达式:

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

更新的 RegEx 演示

正则表达式详细信息:

  • \(\*: 比赛开始(*
  • [\s\S]*?: 匹配 0 个或多个任意字符,包括换行符(非贪婪)
  • \*\): 比赛结束*)

推荐阅读