Regex capture every occurrence of a word within two delimiters

前端 未结 4 1568
自闭症患者
自闭症患者 2021-01-05 15:47

Say I have a long string of text, and I want to capture every time the word this is mentioned within rounded brackets. How could I do that? The following patt

4条回答
  •  感情败类
    2021-01-05 16:25

    the use of .* is going to match every single character in your search string. So what you're actually doing here is greedily matching everything before and after the first occurrence of this found within parentheses. Your current match results probably look a little bit like the following:

    ["(odio this nibh euismod nulla, eget auctor orci nibh vel this nisi. Aliquam this erat volutpat)", "this"]
    

    Where the first item in the array is the entire substring matched by the expression, and everything that follows are your regex's captured values.

    If you want to match every occurrence of this inside the parentheses, one solution would be to first get a substring of everything inside the parentheses, then search for this in that substring:

    # Match everything inside the parentheses
    /\([^\)]*\)/
    
    # Match all occurrences of the word 'this' inside a substring
    /this/g
    

提交回复
热议问题