Regular Expression help

This is the place for queries that don't fit in any of the other categories.

Regular Expression help

Postby tyanderson91 » Fri Jul 12, 2013 4:05 am

I am just starting to get into regular expressions and I really like them. I am having some difficulty though. I want to make a code that can go through my iTunes library and make certain words ('In' and 'The') lowercase, but my sample code isn't changing them at all:
Code: Select all
import re
searchstr="Symphony #9 In E Minor, Op. 95, B 178, \"From The New World\" - 1. Adagio, Allegro Molto"

p3=re.compile(r'(In|The)')

results=p3.sub((r'\g<1>').lower(),searchstr)

if results:
    print results


Can someone help me find the bug?
tyanderson91
 
Posts: 1
Joined: Fri Jul 12, 2013 3:58 am

Re: Regular Expression help

Postby metulburr » Fri Jul 12, 2013 4:44 am

regular expressions are "if anything else doesn't work" sort of thing. If there is another way to do it, you should do it without regexp
Code: Select all
print(searchstr.replace('In', 'in'))


or if replacing a lot:
Code: Select all
searchstr="Symphony #9 In E Minor, Op. 95, B 178, \"From The New World\" - 1. Adagio, Allegro Molto"

replacement = ['In', 'The']
for word in replacement:
    searchstr = searchstr.replace(word, word.lower())

print(searchstr)
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1365
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Regular Expression help

Postby snippsat » Fri Jul 12, 2013 11:02 am

Yes metulburr solution woks fine for that string.
There can be a problem if search is big and you only want "In" and "The",
Because this solution will make lowercase of more than "In" and "The".
It`s possible to write more code to avoid this or use regex.
Code: Select all
searchstr = "In The Intro Then"
replacement = ['In', 'The']
for word in replacement:
    searchstr = searchstr.replace(word, word.lower())

print(searchstr) #in the intro then

A demo with regex.
Code: Select all
import re

def replacement(match):
    return match.group(1).lower()

s = 'In The Intro Then'
print re.sub(r'(In\b|The\b){1}', replacement, s) #in the Intro Then
User avatar
snippsat
 
Posts: 155
Joined: Thu Feb 21, 2013 12:04 am


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 1 guest