简体   繁体   English

正则表达式匹配带括号的单词?

[英]RegExp match word with parenthesis?

I have problem with regular expressions.我对正则表达式有疑问。 I have strings like this:我有这样的字符串:

test(r), testtest(r,r), example, example2, exmp (r,5)

I would like to find all words without blanks between text and the parenthesis.我想找到文本和括号之间没有空格的所有单词。 From the string above, I want to get:从上面的字符串中,我想得到:

test(r), testtest(r,r)

I created this regexp but it catches only brackets with content inside:我创建了这个正则表达式,但它只捕获其中包含内容的括号:

/\(([^\)]+)\)/g

Thanks for all answers.感谢所有答案。

Edit: I am working in Ruby, and this regex works perfectly /\w+\(([^)]+)\)/g .编辑:我在 Ruby 工作,这个正则表达式完美地工作/\w+\(([^)]+)\)/g

What should I do if I would like to separate words with commas between brackets and without?如果我想用括号和不带逗号分隔单词怎么办? For example how do I get this?例如,我如何得到这个?

testtest(r,r) <-with comma
test(r) <-without comma

You can add a \\w+ in front of the pattern: 您可以在模式前面添加\\w+

/\w+\(([^)]+)\)/g

This will match one or more 'word' characters (which includes letters, digits, and underscores) followed by an ( , followed by one or more of any character other than ) , followed by a ) . 这将匹配的一个或多个“字”的字符(包括字母,数字和下划线),随后由( ,接着通过一个或多个以外的任何字符的) ,接着是)

If you want to know want to be able to capture the word that appears before the parentheses separately, you can put it in a group like this: 如果您想知道能够捕获括号前单独出现的单词,可以将其放在这样的组中:

/(\w+)\(([^)]+)\)/g

In your example, this would give group 1: test and group 2: r for the first match and group 1: testtest and group 2: r,r for the second match. 在示例中,这将给予第1组: test和组2: r为第一匹配和组1: testtest和组2: r,r为第二匹配。

Recently had the same issue myself. 我本人最近也遇到过同样的问题。 Doing this solved my problem: 这样做解决了我的问题:

(\w+\([\w, ]+\))

Hope it helps! 希望能帮助到你!

像这样:

/\w+\(\w([,]\w)?\)/g
text = '''test(r), testtest(r,r), example, example2, exmp (r,5)'''
pattern = r'\w+\([^()]+\)'
m = re.compile(pattern)
results = m.finditer(text)
for r in results:
    print(r)

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

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