简体   繁体   English

python findall匹配全部大写的字符串

[英]python findall to match the string that are all capitalized

I am trying to use python re.findall to match string with following conditions: 我正在尝试使用python re.findall将字符串与以下条件匹配:

contain all uppercase letters
have numbers present sometimes

I tried 我试过了

ab_list = re.findall(r'([A-Z]+)(\.\d+)', text)

but this does not return anything. 但这不会返回任何内容。

You can try this: 您可以尝试以下方法:

import re
s = ["ALL CAPITALS ARE ON", "Some lower, soMe not", "AGAIN, WITH PUNCTIONATION."]
final_data = [i for i in s if re.findall("^[A-Z0-9\W]+$", i)]

Output: 输出:

['ALL CAPITALS ARE ON', 'AGAIN, WITH PUNCTIONATION.']

If you are trying to find words that are all capitalized: 如果您要查找全部大写的单词:

s = ["NOT (LOWER)", "Some lower, soMe not", "AGAIN, WITH PUNCTIONATION.", "young 10 (MODY10)"]
final_data = [b for b in [re.findall("(?<=\().*?(?=\))", i) for i in s] if b and re.findall("^[A-Z0-9\W]+$", b[0])]
final_data = [b for b in [re.findall("\(([A-Z0-9\W])\)", i) for i in s] if b]

Output: 输出:

[['LOWER'], ['MODY10']]

If you have one long string: 如果您有一个长字符串:

s = 'NOT (LOWER)Some lower, soMe notAGAIN, WITH PUNCTIONATION.young 10 (MODY10)'
final_strings = re.findall("\(([A-Z0-9\W]+)\)", s)

Output: 输出:

['LOWER', 'MODY10']

This will find strings containing only uppercase letters, numbers, and spaces. 这将查找仅包含大写字母,数字和空格的字符串。

re.findall('^[A-Z0-9 ]+$', text)

This will return a list containing the string if it matches, otherwise, it returns an empty list. 如果匹配则返回包含字符串的列表,否则返回空列表。 If you just want to detect whether the whole string matches, though, it might be more straightforward to use re.match rather than re.findall . 但是,如果只想检测整个字符串是否匹配,则使用re.match而不是re.findall可能更直接。 That depends on what you're ultimately trying to do. 这取决于您最终想要做什么。

If you want to instead find the individual words, you might want: 如果要查找单个单词,则可能需要:

re.findall('([A-Z0-9]+)', text)

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

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