简体   繁体   English

在字符串中的括号之间搜索内容

[英]Search for content between parenthesis in a string

I want to find text just only inside (), but indexOf return full key value 我只想在()内查找文本,但indexOf返回完整键值

var str = "some textsome textsome text(texttext)some text"
var arrSplit = str.split(' ')
for(var i = 0; i < arrSplit.length; i++){
    if(arrSplit[i].indexOf('(') >= 0) {
        console.log(arrSplit[i])
    }
}

result 结果

text(texttext)some 文字(texttext)一些

I need 我需要

(texttext) (文字文字)

To do it only using split() (provided there is only one such pattern in the string): 仅使用split()可以做到这一点(假设字符串中只有一个这样的模式):

str.split('(')[1].split(')')[0]

..and using RegEx: ..并使用RegEx:

str.match(/\([a-z]*\)/ig)        // returns array containing all matches

Try a regex : 尝试一个正则表达式

str.match(/\([A-Za-z]*\)/g); // will match all occurrences

You can add more the the part in [] depending on what you need to match. 您可以根据需要匹配的内容在[]添加更多部分。 For example, 0-9 if you want to include numbers. 例如,如果要包括数字,则为0-9 Just avoid using .* instead, because this will match something like "(test) nope! (test)" as one block. 只需避免使用.* ,因为这会将"(test) nope! (test)"作为一个块进行匹配。

Essentially, the gist of this regex is that you want all upper/lower case letters between parenthesis. 本质上,此正则表达式的主旨是您希望括号之间的所有大写/小写字母都正确。 The parentheses has to be escaped (hence \\( instead of ( ) because parentheses represent grouping in a regex. 括号必须转义(因此\\(而不是( ),因为括号表示正则表达式中的分组。

Simply try \\(.*?\\) ( RegEx ). 只需尝试\\(.*?\\)RegEx )。

 var str = "some textsome textsome text(texttext)some text" str = str.match(/\\(.*?\\)/); console.log(str[0]); 

OR apply in your implementation: 在您的实现中应用:

 var str = "some textsome textsome text(texttext)some text" var arrSplit = str.split(' ') for(var i = 0; i < arrSplit.length; i++){ if(arrSplit[i].indexOf('(') >= 0) { var res = arrSplit[i].match(/\\(.*?\\)/); console.log(res[0]) } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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