使用Python 2.7,想要使用正则表达式来查找给定字符串的Hello部分。 规则是, Hello可能在模式中以{(1N) , {(2N) (直到10N )或它们的组合{(1N,2N,3N,4N)开头,并以}结尾。
除了匹配Hello部分,我还想知道1N匹配, 2N匹配或10N匹配,还是1N或2N匹配。
任何解决方案都很受欢
Some content {(1N,2N,3N,4N) Hello } Some content Some content {(1N) Python } Some content Some content {(2N) Regex } Some content在第一个例子中,我想知道1N , 2N , 3N , 4N匹配,匹配的字符串是Hello ;
在第二个例子中,我想知道1N匹配,匹配的字符串是Python ; 在第3个例子中,我想知道2N匹配,匹配的字符串是Regex ;
问候,林
Using Python 2.7, want to use regular expression to find the Hello part of a given string. The rule is, Hello maybe in the pattern starts with {(1N), {(2N) (until 10N), or combination of them {(1N,2N,3N,4N), and ends with }.
Besides match the Hello part, I also want to know if 1N match, or 2N match or 10N match, or either 1N or 2N match.
Any solutions are appreciated.
Some content {(1N,2N,3N,4N) Hello } Some content Some content {(1N) Python } Some content Some content {(2N) Regex } Some contentIn the first example, I want to know 1N,2N,3N,4N matches, and the matched string is Hello;
In the 2nd example, I want to know 1N matches, and matched string is Python; In the 3rd example, I want to know 2N matches, and matched string is Regex;
regards, Lin
最满意答案
In [82]: string = "Some content {(1N,2N,3N,4N) Hello } Some content" In [83]: result = re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string) In [84]: nums = re.findall(r"10N|[1-9]N", result[0][0]) In [85]: nums Out[85]: ['1N', '2N', '3N', '4N'] In [86]: matchString = result[0][1] In [87]: matchString Out[87]: 'Hello'对于新字符串:
In [1]: import re In [2]: string = "{(1N,2N,3N,4N) Hello } Some Content {(5N) World }" In [3]: re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string) Out[3]: [('(1N,2N,3N,4N)', 'Hello'), ('(5N)', 'World')] In [4]: result = re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string) In [5]: nums = [re.findall(r"10N|[1-9]N", item[0]) for item in result] In [6]: nums Out[6]: [['1N', '2N', '3N', '4N'], ['5N']] In [7]: matchString = [s[1] for s in result] In [8]: matchString Out[8]: ['Hello', 'World'] In [82]: string = "Some content {(1N,2N,3N,4N) Hello } Some content" In [83]: result = re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string) In [84]: nums = re.findall(r"10N|[1-9]N", result[0][0]) In [85]: nums Out[85]: ['1N', '2N', '3N', '4N'] In [86]: matchString = result[0][1] In [87]: matchString Out[87]: 'Hello'For the new string:
In [1]: import re In [2]: string = "{(1N,2N,3N,4N) Hello } Some Content {(5N) World }" In [3]: re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string) Out[3]: [('(1N,2N,3N,4N)', 'Hello'), ('(5N)', 'World')] In [4]: result = re.findall(r"(\((?:(?:10|[1-9])N(?:,|\)))+)\s*(\w+)", string) In [5]: nums = [re.findall(r"10N|[1-9]N", item[0]) for item in result] In [6]: nums Out[6]: [['1N', '2N', '3N', '4N'], ['5N']] In [7]: matchString = [s[1] for s in result] In [8]: matchString Out[8]: ['Hello', 'World']更多推荐
发布评论