简体   繁体   中英

Regex - Capture anything within parentheses and brackets

I'm really bad at regex and I'm not sure what to do with this. I want to capture anything within () or [] (including the brackets) and nothing after. For example if I type [this is text] I want it to return exactly that. Also I have a json full of terms the user types. If the term is not on the json then it shouldn't print. This is the snippet of code which relates to the regex.

let sf_re = /(?:(,)\s+|\s+(xx)\s+)|\+|(,)/    
        if (document.querySelector(".images")){
          document.querySelector(".images").innerHTML = ""
            for(var i=0;i<item.length;i++){
                if(/(\[(.*?)\]|\((.*?)\))/.test(item[i])){
                    let text = item[i]
                    let note = document.createElement("span")
                    note.innerHTML = String(text)
                    document.querySelector(".images").appendChild(note)
                }

Here is an example of what happens

The only thing that should show is [cat cat cat] . "dog" should not appear at all because it's not on my list. In regexr it seems to work fine. I'm not sure what to add.

Edit: I think that my original post had insufficient information. The user types into an input bar which is split into an array using .split() . My main goal is to allow the user to add small lines of text. For example if my json has the terms "cat", "dog", and "pig" and the user types those terms, then it will return something. This is what I get using the suggestions below. Notice how "f" returns an arrow the first time, but not the second time. I'm not sure why this happens. I may be using "match" wrong. I tried this and I get an error "cannot read property of undefined":

let regex = /(\[(.*?)\]|\((.*?)\))/
if (document.querySelector(".images")){
          document.querySelector(".images").innerHTML = ""
            for(var i=0;i<item.length;i++){
                if(item[i].match(regex)[0]){
                    let text = item[i]
                    let note = document.createElement("span")
                    note.innerHTML = String(text)
                    document.querySelector(".images").appendChild(note)
                }

Also I have a json full of terms the user types. If the term is not on the json then it shouldn't print.

You can use

obj.hasOwnProperty(prop);

This will let you know whether the object contains the specified prop. Here is an Example -

 var x = { y: 10 }; alert(x.hasOwnProperty("y")); //true alert(x.hasOwnProperty("z")); //false 

Here are two simple regexs you can use. One matches on brackets and the other matches on parenthesis.

The third is a combination that checks for either. Keep in mind, however, that you'll only ever be able to one of each for [ ] and ( ) . If you're accepting multiple of either kind, then the regex will break since it'll return all characters between the outermost ones.

Using match it gives back an array, so if you know you're only getting a single result, you can grab the first item, like in result and result2. If not, you can just deal with the array of results like in result3.

 const regex = /\\[.*\\]/ const regex2 = /\\(.*\\)/ const regex3 = /(\\[.*\\])|(\\(.*\\))/g const result = ("[cat cat cat]dog").match(regex3)[0]; const result2 = ("banana(cat cat)horse").match(regex3)[0]; const result3 = ("alfred[cat cat cat]banana(dog dog)").match(regex3); console.log(result); //[cat cat cat] console.log(result2); //(cat cat) console.log(result3); // [ '[cat cat cat]', '(dog dog)' ] 

The . character matches anything, and the * will repeat 0 or more times. The \\ character can be used to escape [ , ] , ( and ) as necessary (and any other special regex character). The g at the end will check across the entire string.

Hopefully that should be enough to get you un-stuck.

The regex is [\\[|\\(](.*)[\\]\\)]

Explanation: read '[' or '(', then read anything until there is a ']' or a ')'

 var regexp = /[\\[|\\(](.*)[\\]\\)]/; var match = ("[cat cat cat]dog").match(regexp); console.log(match[1]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM