looking for a regular expression

  • Thread starter ¨ì©³¦b²Ö¤°»ò°Ú¡H
  • Start date
¨

¨ì©³¦b²Ö¤°»ò°Ú¡H

I want words between 2 nearby commas with a specific word in them.

For example,in the text blow:

"We the people of the United States, in order to form a more perfect union,
establish justice, insure domestic tranquility,......"

I want "justice" and the words between the 2 nearest commas, which is

establish justice

All I can come up with is

r",(.*?justice.*?),"

but the result is

in order to form a more perfect union, establish justice

Apreciate any help.
--
¤Ò§LªÌ¤£²»¤§¾¹ª«©Î´c¤§¬G¦³¹DªÌ¤£³B§g¤l©~«h¶Q¥ª¥Î§L«h¶Q¥k§LªÌ¤£²»¤§¾¹«D§g¤l
¤§¾¹¤£±o¤w¦Ó¥Î¤§«ï²H¬°¤W³Ó¦Ó¤£¬ü¦Ó¬ü¤§ªÌ¬O¼Ö±þ¤H¤Ò¼Ö±þ¤HªÌ«h¤£¥i±o§Ó©ó¤Ñ¤U
¨o¦N¨Æ©|¥ª¤¿¨Æ©|¥k°¾±N­x©~¥ª¤W±N­x©~¥k¨¥¥H³à§³B¤§±þ¤H¤§²³¥H«s´dª_¤§¾Ô³Ó¥H
³à§³B¤§¹D±`µL¦W¾ëÁö¤p¤Ñ¤U²ö¯à¦Ú«J¤ý­Y¯à¦u¤§¸Uª«±N¦Û»«¤Ñ¦a¬Û¦X¥H­°¥ÌÅS¥Á²ö
¤§¥O¦Ó¦Û§¡©l¨î¦³¦W¦W¥ç¬J¦³¤Ò¥ç±Nª¾ 210-64-83-81.adsl.dynamic.seed.net.tw®ü
§@ªÌ¦b 06/08/01 21:35:48 ±q 210-64-83-81.adsl.dynamic.seed.net.tw ­×§ï³o½g¤å³¹
§@ªÌ¦b 06/08/01 21:36:28 ±q 210-64-83-81.adsl.dynamic.seed.net.tw ­×§ï³o½g¤å³¹
§@ªÌ¦b 06/08/01 21:37:08 ±q 210-64-83-81.adsl.dynamic.seed.net.tw ­×§ï³o½g¤å³¹
§@ªÌ¦b 06/08/01 21:38:04 ±q 210-64-83-81.adsl.dynamic.seed.net.tw ­×§ï³o½g¤å³¹
 
D

Duncan Booth

¨ì©³¦b²Ö¤°»ò°Ú¡H said:
I want "justice" and the words between the 2 nearest commas, which is

establish justice

All I can come up with is

r",(.*?justice.*?),"

but the result is

in order to form a more perfect union, establish justice

Apreciate any help.

",([^,]*justice[^,]*),"

But this is simpler if you don't use a regular expression:
s = "We the people of the United States, in order to form a more perfect union, establish justice, insure domestic tranquility,......"
[phrase for phrase in s.split(',') if 'justice' in phrase ]
[' establish justice']
 
T

Thomas Nelson

How about
my_string = "We the people of the United States, in order to form a
more perfect union, establish justice, insure domestic
tranquility,......"
print (x for x in my_string.split(",") if "justice" in x).next()

This isn't a regular expression, but it gives what you're looking for.

THN
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top