Regex

From The World according to Vissie
Jump to navigation Jump to search

Regular Expression [regex]

regular expressions make this easy ...

[A-Z] will match exactly one character between A and Z
\d+ will match one or more digits
() group things (and also return things... but for now just think of them grouping)
+ selects 1 or more
{1} match 1 character 
r is used for the string literal to make it trivial to have backslashes inside the regex
name = ["AA1B1", "djdd", "B2C4", "C2H2", "jdoi","1A4V"]
# Match names.
for element in name:
    m = re.match("(^[A-Z]{1}[0-9]{1})", element)
    if m:
       print(m.groups())
('B2',)
('C2',)


string = ["ftp://www.somewhere.com/over/the/rainbow/image.jpg","http://www.somewhere.com/over/the/rainbow/image.gif","http://www.somewhere.com/over/the/rainbow/image.png"] for element in string:

    m = re.match(r'(ftp|http)://.*\.(jpg|png)$', element)
    #m = re.match('^ftp://(.*?)\.jpg$', element)
    #m = re.match(r"^(http).*(png|gif)$",element)
    if m:
       print(m.groups())
       print(element)
('ftp', 'jpg')
ftp://www.somewhere.com/over/the/rainbow/image.jpg
('http', 'png')
http://www.somewhere.com/over/the/rainbow/image.png


name = ["AA1B1", "djdd", "0B2C4", "4C2H2", "jdoi","1A4V"]

for element in name:

   m = re.match("^[a-zA-Z]+.*", element)
   if m:
       print(element)
AA1B1
djdd
jdoi