Skip to main content
 首页 » 编程设计

Python 正则表达式。在一句话中找一句话

2025年05月04日27pander-it

我试图在“Chris 和 34K 其他人”这句话中找到表达方式“K others”

我试过正则表达式,但它不起作用:(

import re 
 
 
value = "Chris and 34K others" 
 
m = re.search("(.K.others.)", value) 
 
if m: 
    print "it is true" 
else: 
    print "it is not" 

请您参考如下方法:

猜测您正在抓取网页“您和 34k 其他人在 Facebook 上喜欢这个”,并且您正在将“K 其他人”包装在捕获组中,我会直接跳到如何获取号码:

import re 
 
value = "Chris and 34K others blah blah" 
 
# regex describes 
# a leading space, one or more characters (to catch punctuation) 
# , and optional space, trailing 'K others' in any capitalisation 
m = re.search("\s(\w+?)\s*K others", value, re.IGNORECASE) 
 
if m: 
    captured_values = m.groups() 
    print "Number of others:", captured_values[0], "K" 
else: 
    print "it is not" 

Try this code on repl.it

这还应该包括大写/小写字母 K、带逗号的数字(1,100K 人)、数字和 K 之间的空格,并且在“其他”之后有文本或没有文本时都有效。