4 Replies - 1655 Views - Last Post: 23 September 2012 - 05:21 AM Rate Topic: -----

#1 yelo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-September 12

Regular expressions - multiple conditions to search for pattern

Posted 19 September 2012 - 01:16 AM

Hi,

I'm trying to write a regular expression to match a string which contains numbers.

The string can be any sentence with a number in any format, eg., 122.5, $1000, 90%.

Could anyone please help?

Thanks in advance,
Ami
Is This A Good Question/Topic? 0
  • +

Replies To: Regular expressions - multiple conditions to search for pattern

#2 yelo  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 19-September 12

Re: Regular expressions - multiple conditions to search for pattern

Posted 19 September 2012 - 02:09 AM

This is what I tried. I have a file containing a few lines, which I have in a list.


pattern = None
file = open('file.txt','r')
for line in file:
    pattern = re.search('\S*'+ (('\$?(\d+)\.?(\d?)') or ('(\d+)\s?(\d+)/(\d+)') or ('(\d+)\.?(\d?)%?')), line)
    if pattern:
        print pattern.split("text")[-1]




I'm not sure whether we could use "or" operators within regular expressions. I am a newbie and I have been trying to figure this out, but could not find anything that was of help to me.

Your help is appreciated. :)

Thanks,
Ami
Was This Post Helpful? 0
  • +
  • -

#3 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 756
  • View blog
  • Posts: 1,990
  • Joined: 23-December 08

Re: Regular expressions - multiple conditions to search for pattern

Posted 20 September 2012 - 09:53 PM

I'd be genuinely impressed with Python if it was smart enough to make that work. I think a better solution would be to pipe those regular expressions together. You can find more information on how to do that here.

This post has been edited by JackOfAllTrades: 23 September 2012 - 05:21 AM
Reason for edit:: Used bit.ly on link to fix link bug

Was This Post Helpful? 0
  • +
  • -

#4 alpertt  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 02-May 12

Re: Regular expressions - multiple conditions to search for pattern

Posted 23 September 2012 - 04:53 AM

could you fix the link, some tag broke it i guess.
Was This Post Helpful? 0
  • +
  • -

#5 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5954
  • View blog
  • Posts: 23,217
  • Joined: 23-August 08

Re: Regular expressions - multiple conditions to search for pattern

Posted 23 September 2012 - 05:21 AM

Done.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1