如何验证字符串仅包含字母、数字、下划线和破折号? [英] How do I verify that a string only contains letters, numbers, underscores and dashes?

查看:54
本文介绍了如何验证字符串仅包含字母、数字、下划线和破折号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我遍历字符串中的所有字符,我知道该怎么做,但我正在寻找一种更优雅的方法.

I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.

推荐答案

正则表达式只需很少的代码即可解决问题:

A regular expression will do the trick with very little code:

import re

...

if re.match("^[A-Za-z0-9_-]*$", my_little_string):
    # do something here

这篇关于如何验证字符串仅包含字母、数字、下划线和破折号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆