Javascript open和closed语句({and}-ish)中的匹配

Javascript open和closed语句({and}-ish)中的匹配,javascript,regex,Javascript,Regex,我有一个包含函数和全局常量变量列表的文件 const native func foo takes nothing returns nothing const native func bar takes nothing returns nothing public const boolean foo1 = false const boolean bar1 = true // etc etc ..... (comment line) const text foo68

我有一个包含函数和全局常量变量列表的文件

const native func foo takes nothing returns nothing
const native func bar takes nothing returns nothing

public

   const boolean foo1 = false
   const boolean bar1 = true

   // etc etc ..... (comment line)

   const text foo68 = "Hello"
   const text bar69 = "World"

   const   int _pi = 3.14159265359
   const   int        _tau = 2*_pi

endpublic

const native func xxx takes text str returns boolean
const native func yyy takes int val returns text
native func zzz takes float val returns int

public

   // check if it works for multiple public.
   const text heh = "hello"
   const text  hehe = zero

endpublic

const native func qqq takes text str returns int
这是我目前的正则表达式

(?:const\s+\w+\s+)(\w+)
我的目标是在
public
endpublic
中获取变量名

结果必须是这样的:

foo1
bar1
foo68
bar69
heh
hehe
是否可以匹配特定打开和关闭标记内的字符串?如果是,如何进行

是否可以匹配特定打开和关闭标记内的字符串?如果是,如何进行

请记住,正则表达式只是程序员可以使用的众多工具之一。它可以与其他任何工具混合使用。例如,解决问题的一种方法是使用两个循环,其中一个使用正则表达式:

  • 阅读每一行,直到找到“public”
  • 阅读每一行,用正则表达式解析变量名,直到找到“endpublic”
  • 用于应用正则表达式并收集所有结果,而不必在循环中使用exec。这样更方便。检查底部的兼容性表。支持相对较新

    Regex从public()endpublic提取,然后使用应用另一个Regex提取常量名称并将所有结果展平到一个数组中。
    从\w切换到[a-zA-Z0-9]以不包括带有uuu的名称。
    spread操作符收集数组中的结果,以便我可以使用flatMap和map

    console.log(
    […data.matchAll(/public([\S\S]*?)endpublic/g)].flatMap(
    pub=>[…pub[1]。匹配所有(/(?:const\s++\w++\s+([a-zA-Z0-9]+)/g)]。映射(x=>x[1]))
    )
    
    data=`const native func foo take nothing返回nothing
    const native func bar不接受任何内容也不返回任何内容
    公众的
    常量布尔值foo1=false
    常量布尔bar1=true
    //等等。。。。。(评论行)
    const text foo68=“你好”
    const text bar69=“世界”
    常数int_pi=3.14159265359
    常数int _tau=2*_pi
    最终公众
    const native func xxx接受文本str返回布尔值
    const native func yyy接受int val返回文本
    本机func zzz接受浮点val返回int
    公众的
    //检查它是否适用于多个公共应用程序。
    const text heh=“你好”
    常量文本hehe=零
    最终公众
    const native func qqq接受文本str返回int`