如何检查以$符号开头并且可以包含字母和正数的字符串
我正在尝试检查字符串:
- 必须从 $ 符号开始,
- 后跟 $ 符号,它可以有字母和数字(无符号)。
- 不允许有特殊字符和空格(开头的$符号除外)
is_match = re.search("^\$[a-zA-Z0-9]", word)
问题一我面临
它接受字符串中的特殊字符和空格。
I am trying to check string which:
- Must start from $ symbol
- followed by $ symbol it can have alphabets and digits(no sign).
- No Special character and space are allowed(except $ symbol in the beginning)
is_match = re.search("^\$[a-zA-Z0-9]", word)
Problem I am facing
It is accepting special characters and space in my string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将您的正则表达式修改为:
^
断言行开头的位置$
匹配\$
与开头[a -zA-Z0-9]+
匹配这些字符一次或多次$
在行尾断言位置说明:
"$abc123456789"
所以你的字符串如何结束并不重要。我刚刚在正则表达式末尾添加了
$
,该正则表达式断言位置为行尾
和数字,没有别的。
来源(运行):
演示
Modified your regex to this:
^
asserts position at the start of a line\$
matches the character$
in the beginning[a-zA-Z0-9]+
matches these characters for one or more times$
asserts position at the end of a lineExplanation:
"$abc123456789"
so it didn't matter how your strings ended with. Ijust added
$
in the end to your regex which asserts position atthe end of a line
and numbers and nothing else.
Source (run ):
Demo
Python在Regex引擎看到它们之前,请处理常规字符串中的后斜线。通常在正则表达式周围使用原始字符串(通常是将所有背斜线加倍)。
另外,您的正则只需检查美元符号之后(至少)一个字母数字字符(至少)。如果要检查整个字符串,则需要创建一个对整个字符串的正则表达式。
或者
Backslashes in regular strings are processed by Python before the regex engine gets to see them. Use a raw string around regular expressions, generally (or double all your backslashes).
Also, your regex simply checks if there is (at least) one alphanumeric character after the dollar sign. If you want to examine the whole string, you need to create a regular expression which examines the whole string.
or