473,563 Members | 2,904 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problema con le RE....

Problema con le RE....
Ho questa stringa "3 HOURS, 22 MINUTES, and 28 SECONDS" e la devo
'dividere' nelle sue tre parti "3 HOURS", "22 MINUTES", "28 SECONDS".
La cosa mi viene molto con le RE...(inutile la premessa che sono molto
alle prime armi con RE e Python)
Qesito perchè se eseguo questo codice
regex=re.co mpile("[0-9]+ (HOUR|MINUTE|SE COND)")
print regex.findall(" 22 MINUTE, 3 HOUR, AND 28 SECOND") ottengo come output:
['MINUTE', 'HOUR', 'SECOND']
e non come mi aspettavo:
['3 MINUTE', '22 HOUR', '28 SECOND']


Saluti e grazie mille...
Alessandro

Jan 9 '06 #1
2 1273
Alessandro wrote:
Problema con le RE....
Ho questa stringa "3 HOURS, 22 MINUTES, and 28 SECONDS" e la devo
'dividere' nelle sue tre parti "3 HOURS", "22 MINUTES", "28 SECONDS".
La cosa mi viene molto con le RE...(inutile la premessa che sono molto
alle prime armi con RE e Python)
Qesito perchè se eseguo questo codice
>>>>regex=re.co mpile("[0-9]+ (HOUR|MINUTE|SE COND)")
>>>>print regex.findall(" 22 MINUTE, 3 HOUR, AND 28 SECOND") ottengo come output:
>>>> ['MINUTE', 'HOUR', 'SECOND']
e non come mi aspettavo:
>>>> ['3 MINUTE', '22 HOUR', '28 SECOND']
Saluti e grazie mille...
Alessandro

Would probably be slightly easier had you written it in english, but
basically the issue is the matching group.

A match group is defined by the parenthesis in the regular expression,
e.g. your match group is "(HOUR|MINUTE|S ECOND)", which means that only
that will be returned by a findall.

You need to include the number as well, and you can use a non-grouping
match for the time (with (?: ) instead of () ) to prevent dirtying your
matched groups.
pattern = re.compile(r"([0-9]+ (?:HOUR|MINUTE| SECOND))")
Other improvements:
* \d is a shortcut for "any digit" and is therefore equivalent to [0-9]
yet slightly clearer.
* You may use the re.I (or re.IGNORECASE) to match both lower and
uppercase times
* You can easily handle an optional "s"

Improved regex:
pattern = re.compile(r"(\ d+ (?:hour|minute| second)s?)", re.I)
pattern.findall ("3 HOURS 22 MINUTES 28 SECONDS") ['3 HOURS', '22 MINUTES', '28 SECONDS'] pattern.findall ("1 HOUR 22 MINUTES 28 SECONDS")

['1 HOUR', '22 MINUTES', '28 SECONDS']

If you want to learn more about regular expressions, I suggest you to
browse and read http://regular-expressions.info/ it's a good source of
informations, and use the Kodos software which is a quite good Python
regex debugger.
Jan 9 '06 #2
Thanks for the reply it's ok!!!
The language? I selected the wrong newsgroup in my
newsreader!!!.. .sorry...

Thanks...

Alessandro...

Jan 9 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2645
by: Sergio | last post by:
Olá pessoal Estou com um problema num relatório, quando mando imprimir ou visualizar um determinado relatório com um subrelatório que tem varios campos entre os quais quant, preço, total, fazendo a soma QUANT*PREÇO vai me dar o TOTAL. Em subtotal tenho a expressao =Soma()mas ao puxar esse valor para um campo no relatório se nao tiver nenhum...
0
2153
by: StellaAzzurra | last post by:
Salve, premettendo che non sono un esperta di access, vi pongo il mio problema. Sto facendo una rubrica con access ed avrei la necessità di fare in modo che se ad esempio un mio clienti avesse 5 numeri di telefono dell'ufficio, questi potessero essere visualizzati tutti su una stessa cella, ovviamente uno alla volta, ed avrei pensato al...
1
3282
by: Juan | last post by:
Hola Grupo! Tengo el siguiente problema. Quiero desarrollar una aplicación ASP.NET con Visual Studio.NET y resulta que cuando quiero crear una me aparece el siguiente mensaje **************************************************************************** **************************************************************** Visual Studio .Net ha...
1
2974
by: teo_teo_teo | last post by:
ciao, in un campo "file" di un documento xml ho qualcosa del tipo ..\folder\file.pdf ovviamente nn posso cambiare il modo in cui il folder e il file sono visualizzti in quel tag perché il file xml é generato automaticamente e sarebbe tropppo lungo modificarlo.. ora, devo visualizzare separatamente il file e il folder sto provando ad usare...
0
468
by: teo_teo_teo | last post by:
ciao, in un campo "file" di un documento xml ho qualcosa del tipo ..\folder\file.pdf ovviamente nn posso cambiare il modo in cui il folder e il file sono visualizzti in quel tag perché il file xml é generato automaticamente e sarebbe tropppo lungo modificarlo.. ora, devo visualizzare separatamente il file e il folder sto provando ad usare...
0
7583
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7888
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7642
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6255
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5484
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1200
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
924
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.