如何检查以$符号开头并且可以包含字母和正数的字符串

发布于 2025-01-21 00:57:23 字数 236 浏览 1 评论 0原文

我正在尝试检查字符串:

  1. 必须从 $ 符号开始,
  2. 后跟 $ 符号,它可以有字母和数字(无符号)。
  3. 不允许有特殊字符和空格(开头的$符号除外)

is_match = re.search("^\$[a-zA-Z0-9]", word)

问题一我面临

它接受字符串中的特殊字符和空格。

I am trying to check string which:

  1. Must start from $ symbol
  2. followed by $ symbol it can have alphabets and digits(no sign).
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青衫负雪 2025-01-28 00:57:23

将您的正则表达式修改为:

^\$[a-zA-Z0-9]+$
  1. ^ 断言行开头的位置
  2. 中的字符 $ 匹配
  3. \$ 与开头[a -zA-Z0-9]+ 匹配这些字符一次或多次
  4. $ 在行尾断言位置

说明:

  1. 您基本上是在搜索以开头的字符串
    "$abc123456789" 所以你的字符串如何结束并不重要。我
    刚刚在正则表达式末尾添加了 $ ,该正则表达式断言位置为
    行尾
  2. 确保整个字符串仅包含字母
    和数字,没有别的。

来源(运行):

    regex = r"^\$[a-zA-Z0-9]+$"
    test_str = ("$abc123     ")
    is_match = re.search(regex, test_str)
    if(is_match):
        print("Yes")
    else:
        print("No")

演示

Modified your regex to this:

^\$[a-zA-Z0-9]+$
  1. ^ asserts position at the start of a line
  2. \$ matches the character $ in the beginning
  3. [a-zA-Z0-9]+ matches these characters for one or more times
  4. $ asserts position at the end of a line

Explanation:

  1. You were basically searching for string that started with
    "$abc123456789" so it didn't matter how your strings ended with. I
    just added $ in the end to your regex which asserts position at
    the end of a line
  2. It makes sure that the entire string will only consist alphabets
    and numbers and nothing else.

Source (run ):

    regex = r"^\$[a-zA-Z0-9]+
quot;
    test_str = ("$abc123     ")
    is_match = re.search(regex, test_str)
    if(is_match):
        print("Yes")
    else:
        print("No")

Demo

十六岁半 2025-01-28 00:57:23

Python在Regex引擎看到它们之前,请处理常规字符串中的后斜线。通常在正则表达式周围使用原始字符串(通常是将所有背斜线加倍)。

另外,您的正则只需检查美元符号之后(至少)一个字母数字字符(至少)。如果要检查整个字符串,则需要创建一个对整个字符串的正则表达式。

is_match = re.search(r"^\$[a-zA-Z0-9]+$", word)

或者

is_match = re.search("^\\$[a-zA-Z0-9]+$", word)

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.

is_match = re.search(r"^\$[a-zA-Z0-9]+
quot;, word)

or

is_match = re.search("^\\$[a-zA-Z0-9]+
quot;, word)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文