Search code examples
pythonregexpython-re

How to check string start with $ symbol and can have alphabet and positive digit


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.


Solution

  • 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]+$", word)
    

    or

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