0

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.

2 Answers2

3

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]+$"
    test_str = ("$abc123     ")
    is_match = re.search(regex, test_str)
    if(is_match):
        print("Yes")
    else:
        print("No")

Demo

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
2

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)
tripleee
  • 175,061
  • 34
  • 275
  • 318