regex这个代码是python的

2024-05-19 19:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个字符串:

questioncode = YED_q2_a_10

我想检查字符串是否以下划线结尾,然后是int

i.e. "_293" 

我的尝试:

codesplit = questioncode.split('_')[-1]

if codesplit.isdigit():
    print "true"
else:
    print "false"

正如你所看到的,这不是我想要的,我相信正则表达式是解决方案。你知道吗


Tags: 字符串falsetrueif结尾解决方案elseint
3条回答
import re

if re.match('.*_[0-9]+$', 'YED_q2_a_10'):
    print "true"
else
    print "false"

re.search()试试这个

questioncode = "YED_q2_a_10"
if(re.search("_\d+$", questioncode)):
    print "yes"

\d+表示出现一次或多次的任何数字。$表示字符串的结尾,即anchor。你知道吗

if questioncode.count('_') and questioncode.split('_')[-1].isdigit():
    print 'true'
else:
    print 'false'

很好(我想说首选),为什么要使用正则表达式?它们在这里是绝对不必要的。你知道吗

此语句检查字符串中是否至少有一个下划线,如果有,则拆分字符串,这样就不会出现Index out of range错误。你知道吗

如果需要,您可以按照@qwe的建议,用'_' in questioncode替换questioncode.count('_')。你知道吗

相关问题 更多 >