Python,re模块,查找模式

ui7jx7zq  于 2023-09-29  发布在  Python
关注(0)|答案(5)|浏览(113)

我收到的字符串的模式如下:

"<numbs and upper and lower case letters and _'s>(<numbs and upper and lower case letters and _'s>).<numbs and upper and lower case letters and _'s>"

我需要提取')'之后的内容。有什么方法可以定义re模式并得到我需要的东西吗?我真的不喜欢分裂,总是得到例外。

iklwldmw

iklwldmw1#

如果这些是逐行的,你可以搜索').'序列,并使用这个正则表达式模式获得它后面的所有内容:\).([^\n]+)
因此,在提供的示例中,您将在组1中获得<numbs and upper and lower case letters and _'s>"

3duebb1j

3duebb1j2#

text = "<numbs and upper and lower case letters and _'s>(<numbs and upper and lower case letters and _'s>).<numbs and upper and lower case letters and _'s>"
split_text = text.split(').')
bxgwgixi

bxgwgixi3#

我认为使用split命令的最佳方法。否则,您可以尝试搜索字符位置并在找到索引后打印字符串:

string = "<numbs and upper and lower case letters and _'s>(<numbs and upper and lower case letters and _'s>).<numbs and upper and lower case letters and _'s>"

index = string.find(")")

if index != -1:
    result = string[index + 1:] ### To exclued also dot
    print(result)
5cnsuln7

5cnsuln74#

代码:

import re

# Sample input string
input_string = "abc_def(123_ABC).xyz_456"

# Define the regular expression pattern
pattern = r'\)\.([a-zA-Z0-9_]+)'

# Use re.search to find the match
match = re.search(pattern, input_string)

# Check if a match was found
if match:
    # Extract the text following ').'
    result = match.group(1)
    print(result)
else:
    print("No match found.")

输入:“abc_def(123_ABC).xyz_456”
输出:“xyz_456”

nnsrf1az

nnsrf1az5#

import re

string = "<numbs and upper and lower case letters and _'s>(<numbs and upper and lower case letters and_ 's>).<numbs and upper and lower case letters and \_'s>"

pattern = '\)\.(.*)'

match = re.search(pattern, string)
print(match.group(1))

相关问题