Josh Morrison
Josh Morrison

Reputation: 7636

Python regular expression: find "com" or "org"

Just want to find first time appearance of "com" OR "org". I have tried:

comIndex = domain.index(r '(?: com|org)')

But it does not work. Could someone correct me?

Upvotes: 1

Views: 253

Answers (4)

eyquem
eyquem

Reputation: 27585

import re

pat = re.compile ('com|org')

ch = 'ABCDcomFGH'
print pat.search(ch).start() if pat.search(ch) else -1

ch = 'ABorgWDE'
print pat.search(ch).start() if pat.search(ch) else -1

ch = ':;,"?::/+=&'
print pat.search(ch).start() if pat.search(ch) else -1

result

4
2
-1

Upvotes: 0

highBandWidth
highBandWidth

Reputation: 17316

How about

re.search('(com)|(org)',domain).span()[0]

Upvotes: 4

kennytm
kennytm

Reputation: 523654

I don't think you can use regex like this. Regex in Python is not a built-in feature, and you need to import the re module to use the methods inside.

import re
...
comMatch = re.search('com|org', domain)
if comMatch:
   comIndex = comMatch.start()

Upvotes: 1

yan
yan

Reputation: 20992

import re

comIndex = -1
m = re.search(r'(?:com|org)', domain)
if m:
    comIndex = m.start()
print comIndex

Upvotes: 2

Related Questions