I am learning regex in php but want to try out how the regex in python works. I have not yet moved to the code side of things and for the same reason, i am searching for the regex examples in both php and python.

To start somewhere, i decided to pick three basic tasks : searching the occurring, split, replace.

So here's my string:

"big brown fox jumps over the lazy dog. fox chases mice, dog chases fox."

(i know it's weird string but have to come up with something for example here).


so for searching the occurrance of word "fox", how should i write the code?

import re

st="big brown fox jumps over the lazy dog. fox chases mice, dog chases fox";

Now here is where i am stuck, which methods are to be used for searching the occurrence and for the split or replace?

This does not sound to have any use but here my puny efforts:

import re

st="big brown fox jumps over the lazy dog. fox chases mice, dog chases fox"
print re.findall('fox', st), re.split('fox', st)
#more usefull
print re.findall(r'[^.,!?]+[.,!?]', st)
#in Python
print 'fox' in st, st.count('fox'), st.split('fox')

Output

['fox', 'fox', 'fox'] ['big brown ', ' jumps over the lazy dog. ', ' chases mice, dog chases ', '']
['big brown fox jumps over the lazy dog.', ' fox chases mice,']
True 3 ['big brown ', ' jumps over the lazy dog. ', ' chases mice, dog chases ', '']

Thanks for the pointers, pytony. I was thinking about replacing fox with beever. Here is my code.

st=st.replace('fox','beever');
print st;

so my question is do regular expression offer us search and replace or we have to use .replace() method for the same?

http://www.regular-expressions.info/python.html

import re

st="big brown fox jumps over the lazy dog. fox chases mice, dog chases fox. Firefox is nice to use with foxiness to run Python in Sage workbook."
print re.sub(r'\bfox\b', 'bear', st)
big brown bear jumps over the lazy dog. bear chases mice, dog chases
bear. Firefox is nice to use with foxiness to run Python in Sage
workbook.

That's cool. Thanks pytony.

I was examining your code, just noticed that it is not replacing "fox" in foxiness, is python ignoring occurrence of "fox" in "foxiness" or it just searches for exact match?

r'\b' means that there must be word boundary there, so you can get benefit over the regular Python version of replace which goes everywhere.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.