0

I'm doing practice problems for regular expressions on W3schools and I am supposed to determine if there is a word at the beginning of a string. I don't understand why this code is not working.

def word_at_begin(string):
if bool(re.search(r'^\w+',string)):
    return True
else:
    return False

wordatbegin = "76858 is a word at the beginning of this string"

word_at_begin(wordatbegin)

The above returns True, and I cannot figure out why. To my knowledge, my code is asking for 1 or more characters at the beginning of the string.

dgoodie
  • 17
  • 3
  • 1
    `^\w+` - 1 or more letters, digits or underscores at the start of the string, use http://regex101.com, it will tell you what each pattern means. – Wiktor Stribiżew Feb 21 '20 at 13:35
  • Didnt realize \w meant numbers too. Solved by using ^[a-z]+ | ^[A-Z]+ – dgoodie Feb 21 '20 at 13:42
  • Have you considered `isalpha()`? > `print(wordatbegin[0].isalpha())` and avoid `RegEx`. Plusside: It works for many alphabets! – JvdV Feb 21 '20 at 13:50

0 Answers0