简体   繁体   English

Python Regex,查找两个子串之间的内容

[英]Python Regex, Finding what is in between two substrings

The regex I have right now is: 我现在的正则表达式是:

string="hello (fdd()()()()(()(())()))"
re.match("%s\s*\((.*?)\)$"%re.escape("hello"), string)

And it will work well, the goal of it is to get whatever is inside the brackets. 它会很好地工作,它的目标是获得括号内的任何内容。 In this case: "fdd()()()()(()(())())" 在这种情况下: "fdd()()()()(()(())())"

I would like to make an alteration, the regex should work with this test case 我想做一个改动,正则表达式应该适用于这个测试用例

"hello (hihihi(((())))hihi) { "

There is a curly-brace at the end of it. 最后有一个花括号。 There should always be a curly-brace at the end of the given string therefore the first test case that I showed you will not work anymore (with the new regex that I want). 在给定字符串的末尾应该总是有一个花括号,因此我向你展示的第一个测试用例将不再适用(使用我想要的新正则表达式)。

Try looking at it like this 试着这样看

hello[any amount of space]([get WHATEVER is inside here])[any amount of space]{[any amount of space]

I think that using the dollar sign is what is causing me problems. 我认为使用美元符号是导致我出现问题的原因。 I am obviously not too familiar with using regex, so if anyone can help me that would be great. 我显然不太熟悉使用正则表达式,所以如果有人可以帮助我那将是伟大的。 I am open to any solution including but not limited to other python modules, built in python string features, ect. 我对任何解决方案持开放态度,包括但不限于其他python模块,内置python字符串功能等。

Thanks for your help, 谢谢你的帮助,

I think you could just use "hello\\s*\\((.+)\\)\\s*{" 我想你可以使用"hello\\s*\\((.+)\\)\\s*{"

import re

text = "hello (hihihi(((())))hihi) { "
print re.match(r'hello\s*\((.+)\)\s*{', text).group(1)

gives me 给我

hihihi(((())))hihi

You don't need the ? 你不需要? and $ . $

Try changing your regex to the following: 尝试将正则表达式更改为以下内容:

r"%s\s*\((.*?)\)\s*{" % re.escape("hello")

The only difference here is that the $ was replaced by \\s*{ , which means any amount of whitespace followed by a { . 这里唯一的区别是$被替换为\\s*{ ,这意味着任何数量的空格后跟一个{

Example: 例:

>>> s = "hello (hihihi(((())))hihi) { "
>>> print re.match(r"%s\s*\((.*?)\)\s*{" % re.escape("hello"), s).group(1)
hihihi(((())))hihi

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

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