Regex to match all the strings between two identical strings

后端 未结 2 1107
醉梦人生
醉梦人生 2020-12-02 02:52

E.g. I have this string -- This -- is -- one -- another -- comment -- I want the matched elements to be \"This\", \"is\", \"one\", \"another\", and \"comment\"

2条回答
  •  长情又很酷
    2020-12-02 03:25

    To read all I would use positive look achead:

    const data = '-- This -- is -- one -- another -- comment --'
    
    const readAll = data => {
      const regex =/--\s*(.*?)\s*(?=--)/g
      const found = []
      let temp
      while (temp = regex.exec(data)) {
        found.push(temp[1])
      }
      return found
    }
    
    console.log(readAll(data))

    And to remove comments just do this:

    const data = `-- This -- is -- one -- another -- comment -- this is not a comment`.replace(/--.*--/g, '')
    
    console.log(data)

提交回复
热议问题