f



Using re.VERBOSE, and re-using components of regex?

Hi,

I'm trying to compile a regex Python with the re.VERBOSE flag (so that I can add some friendly comments).

However, the issue is, I normally use constants to define re-usable bits of the regex - however, these doesn't get interpreted inside the triple quotes.

For example:

    import re
    
    TIMESTAMP = r'(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{9})'
    SPACE = r' '
    FOO = r'some_regex'
    BAR = r'some_regex'

    regexes = {
            'data_sent': re.compile("""
                                        TIMESTAMP # Timestamp of our log message
                                        SPACE
                                        FOO # Some comment
                                        SPACE
                                    """, re.VERBOSE),
            'data_received': re.compile("""
                                        TIMESTAMP # Timestamp of our log message
                                        SPACE
                                        BAR # Some comment
                                        SPACE
                                    """, re.VERBOSE),
              }

Is there a way to use CONSTANTS (or at least re-use fragments of my regex), and also use re.VERBOSE so I can comment my regex?

Cheers,
Victor
0
victorhooi (50)
4/16/2013 11:45:20 PM
comp.lang.python 77058 articles. 6 followers. Post Follow

1 Replies
737 Views

Similar Articles

[PageSpeed] 37

On 17/04/2013 00:45, Victor Hooi wrote:
> Hi,
>
> I'm trying to compile a regex Python with the re.VERBOSE flag (so that I can add some friendly comments).
>
> However, the issue is, I normally use constants to define re-usable bits of the regex - however, these doesn't get interpreted inside the triple quotes.
>
> For example:
>
>      import re
>
>      TIMESTAMP = r'(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{9})'
>      SPACE = r' '
>      FOO = r'some_regex'
>      BAR = r'some_regex'
>
>      regexes = {
>              'data_sent': re.compile("""
>                                          TIMESTAMP # Timestamp of our log message
>                                          SPACE
>                                          FOO # Some comment
>                                          SPACE
>                                      """, re.VERBOSE),
>              'data_received': re.compile("""
>                                          TIMESTAMP # Timestamp of our log message
>                                          SPACE
>                                          BAR # Some comment
>                                          SPACE
>                                      """, re.VERBOSE),
>                }
>
> Is there a way to use CONSTANTS (or at least re-use fragments of my regex), and also use re.VERBOSE so I can comment my regex?
>
You could do it like this:

     import re

     constants = {}
     constants['TIMESTAMP'] = r'(?P<timestamp>\d{2}:\d{2}:\d{2}.\d{9})'
     constants['SPACE'] = r'\ ' # Escape the space because it'll be in a 
VERBOSE regex.
     constants['FOO'] = r'some_regex'
     constants['BAR'] = r'some_regex'

     regexes = {
             'data_sent': re.compile("""
                                         {TIMESTAMP} # Timestamp of our 
log message
                                         {SPACE}
                                         {FOO} # Some comment
                                         {SPACE}
                                     """.format(**constants), re.VERBOSE),
             'data_received': re.compile("""
                                         {TIMESTAMP} # Timestamp of our 
log message
                                         {SPACE}
                                         {BAR} # Some comment
                                         {SPACE}
                                     """.format(**constants), re.VERBOSE),
               }

0
python3897 (1417)
4/17/2013 12:16:14 AM
Reply:

Similar Artilces:

Re: Re: Re: Not Using a Text Editor Interface for Mathematica
For some interesting reading take a look at Chapter 2 in Edward R. Tufte's 'Visual Explanations'. Dr. John Snow found the cause of the 1854 Cholera Epidemic in London by FIRST plotting the case data on a map of London, and THEN doing the analysis. In the case of the Challenger Space Shuttle disaster, although they were aware of the potential problem, the technicians never made the proper graphic that related risk to temperature in past launches and thus failed to present a convincing case for not launching. Maybe graphics doesn't always come before analysis, but ...

Re: Re: Use of % notation
I'm not sure what you mean, Jens, by "in the FrontEnd". In any case, I would say avoid the use of % when it refers to output from a different cell. But in doing derivations by a series of calculational steps WITHIN ONE CELL I find that % and %% are extremely useful and completely safe. David Park djmp@earthlink.net http://home.earthlink.net/~djmp/ From: Jens-Peer Kuska [mailto:kuska@informatik.uni-leipzig.de] Avoid the usage of % in the FrontEnd. Regards Jens Hi, I mean, that if you run the Mathematica kernel alone in a command line session or ...

RE: using re.finditer()
Erik Johnson wrote: > I am still fairly new to Python and trying to learn to=20 > put RE's to good use. I am a little confused about the > finditer() method... > ...it doesn't document any restriction about multiline matching, > but it certainly seems to have one... > finditer() doesn't accept a flag like re.DOTALL,=20 > as re.match() and re.search() do. It seems a shame not > to be able to put an otherwise smart design to use. Embed the flag(s) you desire in the regex itself. For example, to include DOTALL, change r'<td.*?>(.*?)</td>' t...

RE: [Info-ingres] Re: Is it possible to use OpenIngres gateway to access Sybase without using cursors?
"DBG" <tore.aasgaard@gmail.com> wrote in message > Hi > > Im administering a Sybase database. The application accessing this > database was originally developed for Ingres, so now the application > which is developed using Ingres OpenRoad is communicating with my > Sybase database via an OpenIngres gateway (Enterprise access I think > is the name). > I've have performance issues with my database, (table locking, high > number of small I/O etc) and from what I can gather this is in my case > related to the use of cursors gateways part. We experienced a lot of locking problems in EA/MSSQL until I put this in the start up code: SELECT :lv_server_class = dbmsinfo('server_class'); IF lv_server_class = 'MSSQL' THEN DIRECT EXECUTE IMMEDIATE 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED'; COMMIT; DIRECT EXECUTE IMMEDIATE 'SET LOCK_TIMEOUT 10000'; COMMIT; ELSEIF lv_server_class = 'Ingres DBMS Server' THEN SET lockmode session WHERE readlock = nolock, timeout = 10; COMMIT; ELSE MESSAGE 'Warning server class ' + lv_server_class + ' not implemented'; ENDIF; "Paul White" <pwhite@peerlessit.com.au> wrote in message news:mailman.1111701677.22482.info-ingres@cariboulake.com... > We experienced a lot of locking problems in EA/MSSQL until I put this in ...

RE: [Info-ingres] Re: Is it possible to use OpenIngres gateway to access Sybase without using cursors? #2
Roy writes: > Err, we do all know what READ UNCOMMITTED means, I hope? (There is a very > good reason why Ingres makes the transaction implicitly read-only when you > do that.) And also, it is not clear to me why changing the isolation level > of just the next transaction would solve anything much. Do you perhaps > intend that to be SET SESSION ISOLATION LEVEL? Well, err, I used to think so before we started using EA/MSSQL. Here is the MSSQL syntax. No session keyword. It affects all transactions for the session. SET TRANSACTION ISOLATION LEVEL { READ COMMITTED | READ UNCOMMITTED | REPEATABLE READ | SERIALIZABLE } When the code was converted to run over both ingres and EA/MSSQL, we discovered serious locking contention everywhere. The "SET lockmode session.." statement was apparently ignored by the gateway. After some research, the programmers decided to fix it by putting a commit after every select statement - even in the middle of important business transactions. The work around I discovered after rtfm about two years later. (I was too busy fixing rollbacks that didnt rollback what they were supposed to) It is not ideal but is ok for this app because there is a manual lock indicator to avoid two operators accessing the same account at the same time. Paul "Paul White" <pwhite@peerlessit.com.au> wrote in message news:mailman.1111732922.16542.info-ingres@cari...

RE: [ace-users] Re: Can we use attribute operation methods from another component? How?
Hi, > -----Original Message----- > From: owner-ace-users@cse.wustl.edu > [mailto:owner-ace-users@cse.wustl.edu] On Behalf Of Douglas C. Schmidt > Sent: Monday, April 17, 2006 7:26 AM > To: billdavidcn@gmail.com > Cc: ace-users@cs.wustl.edu > Subject: [ace-users] Re: Can we use attribute operation > methods from another component? How? > > > Hi David, > > >> Here, I mean that if we communicate with other components with just > >> facet/receptacle or event, it's possible to reuse this component > >> for other applications > > Yes, of course. > > >> since we can keep us from accessing the partner component > >> directly (all communication is done indirectly by container). > > Right. > > >> As long as another component act as a "partner" of this component, > >> it can communicate with this component. But if we directly access > >> another component in our component, we must hard code the objective > >> component name in our implementation. It will block us to reuse > >> this component in another application. So currently, I think if we > >> want to change another component's attribute, we should still do it > >> using facets providing by that component. Am I right? > > No, not really. Component attributes are operations just like any > other type...

Re: Using BIND
----- Original Message Follows ----- > > Danny, many thanks and sorry to disappoint you, but I'm not going > ahead with this. Why? > > - the apparent lack of any online documentation for the Windows > version of BIND > The online documentation is in the binary kit: Bv9ARM*.html is the BIND documentation. > - the lack of any user manual for BIND - at least I didn't see any > pointers on the page: http://www.isc.org/index.pl?/sw/bind/ I'm not > going to run the installer just to get the documentation - it should > be online like the NTP do...

Re: Using BIND
----- Original Message Follows ----- > mayer wrote: > [] > > The ARM is available online, but you also have your own local copy. > >> From Google I found this online: > > http://www.fiveanddime.net/bind-9/bind-9.3.1/doc/arm/ > > > > Danny > > Thanks for that, Danny. Arrgh! I don't know if it's just my Web > browser, but all I get there is a directory list. Perhaps you mean: > > > http://www.fiveanddime.net/bind-9/bind-9.3.1/doc/arm/Bv9ARM.html.html > These HTML pages come with both the Windows binaries and the source....

Re: Using BIND
----- Original Message Follows ----- > mayer wrote: > [] > > I'm not trying to convince you, it's up to you to make you own > > decisions on what makes sense on your own network. I just strongly > > recommend against > > using a hosts file as it's error prone, requires repropogation, is > > vunerable to viruses and can generally not be relied on. One virus I > > saw going around last year made use of it to add bad addresses of > > all of the various virus makers making it impossible to contact them > > to download new virus defi...

Re: Using BIND
----- Original Message Follows ----- > mayer wrote: > [] > >> In my own small network, by the way, I have fixed IP addresses and > >> avoid DHCP. I have made the router start at 192.168.0.100 (or > >> whatever) so there is a space of clear addresses in the > >> 192.168.0.1..99 range that I can assign myself. I have around 10 > >> PCs. This means that I use the HOSTS file to assign names to > >> numbers. > >> > > > > That's silly. Just install BIND on one of your system and have it > > provide the ...

Re: Using BIND
----- Original Message Follows ----- > Brad Knowles wrote: > > > [excellent discussion] > > What can I say but thanks - I knew many of these things but had > forgotten some and not encountered others. The idea of stratum 1 NTP > servers simply referring you further down the line is a fascinating > one! NTP V5? > Most unlikely, the architecture is totally different and it would require some way of each server knowing what's closer to you, network-wise, in order to have have a hope of being possible. Danny > Cheers, > David > > > _____...

Re: Using BIND
----- Original Message Follows ----- > Well, thanks to Danny, Brad and David I have this working. Danny may > wish to note: > > - it doesn't say anywhere in the Windows ReadMeFirst to create the > file named.conf - perhaps an empty one should be supplied in the > correct directory? > I don't want to do that as there's too much risk of overwriting an existing one. > - the required directory \dns\etc\namedb is not automatically created > (although there seem to be no files created there?). > That's optional in how you set up your zones. I don...

RE: how to prevent re-use of passwords
I have a client that has been subject to a security audit by their major client account and I have to respond to several "action items." The client is running SCO 5.0.7 Enterprise with Maintenance Pack 3. I have enabled password aging with a 90-day lifetime and that appears to be working (Users logged off by new installation of nidleout were asked to change their passwords after I set MAXWEEKS=14 in /etc/default/password). i have edited /etc/default/password and set the minimum Password length to 8 characters per the client "action item." But I find no built in wa...

Re: Using BIND
----- Original Message Follows ----- > At 4:27 PM +0000 2005-06-04, David J Taylor wrote: > > > What can I say but thanks - I knew many of these things but had > > forgotten some and not encountered others. > > Not a problem. I'm glad to be able to help. > > > The idea of stratum 1 NTP servers > > simply referring you further down the line is a fascinating one! > NTP V5? > > Actually, I think that the "manycast" solution should do the job > just fine. We just have to get peopl...

Re: Re: Re: Marc Re: Andreessen Re: created Re: the Re: first Re: web Re: browser
no. ...

Re: Re: Using Mathematica notebooks in presentations?
Hi, everyone, This discussion has already been held, and positions of two major group are clear: those preferring specifically Mathematica presentations and those preferring generic PowerPoint-type programs. I am following this discussion with a practical interest of a one doing such presentations and having to be alert. However, at present this new discussion is unfortunately kept on the level of personal tests. These tests (as much as I can see from the present discussion) are very much based on personal Mathematica-programming skills. It is not quite unexpected. Those with greater experience in such a programming see no problems to write a peace of code to make a demonstration for the presentation. But in this case this demonstration will be much better suited for the presentation aim. In contrast, those with a considerably smaller experience realize this also, but will have to spend too much time, and presentation will look much less professional. This dominates the decision and I find that the both groups are right. I think that there are also some problematic things that at present in the both styles of presentations. I am going to note now those I met. I hope with these in focus the discussion may help the Wolfram crew in future. The drawbacks of PowerPoint-oriented presentations are well described by math-presentations followers. I agree 100%, and for this reason I will not comment on this any more. Let me instead formulate few narrow pla...

Re: Re: Informix limitations, should we be using Oracle?
For me too.. ;) but: select null from systables; gives: 201: A syntax error has occurred. I have : Informix Dynamic Server Version 9.30.HC2W8 HP-UX B.11.00 U 9000/856 I could bet the same hapen in 9.4 BTW: select getnull() from systables; Works... ugly but it works... (it's a stored procedure)... and I can live with it. Chucho! -----Original Message----- From: Paul Watson <paul@oninit.com> To: informix-list@iiug.org Date: Mon, 17 Nov 2003 23:36:32 +0000 Subject: Re: Informix limitations, should we be using Oracle? What wrong with select * from table where colname is null; seems to work for me Jean Sagi wrote: > > I read all you post and it was very interesting... > > I have only 2 thing to say and have in count that I don't know anything > about XPS: > > 1. In IDS 9.x, you can't select a NULL, you can use it in an UPDATE, > INSERT or DELETE. You can workaround this by creating an sp sp_genull() > who return a null and that do it... but is ugly... > If XPS can do it... it's good, inf fact there are some very cool > features only in the XPS SQL I wish to have in IDS. > > 2. In IDS there is no FULL OUTER JOIN... in some cases this is very > usefull. If XPS have it it's good. > > As I said, I wish SQL-IDS has more features of XPS-SQL > > Chucho! > > Jack Parker wrote: > > I must have been offlin...

RE: [Info-ingres] Re: What do you use VDBA for?
Hello, I often see vdba used to create tables and indexes in the development cycle. Usually by programmers without Unix or dba skills. It gets used to create and test new vnodes. It would be a pleasant surprise if my programmers started looking at qeps before they released to production. I find it effective in tracking sessions, locks and blocks, but I normally don't run it over my unix production system. I use unix scripts to keep an eye on system and database health. I think the performance monitor puts a bit of a load on the server and it is frustrating when the "background refresh" pops up in the foreground blocking any other activity. I prefer: while /bin/true; do Sleep 10 iisess -rq #show me running queries Done Paul -----Original Message----- From: info-ingres-admin@cariboulake.com [mailto:info-ingres-admin@cariboulake.com] On Behalf Of Roy Hann Sent: Friday, 23 September 2005 9:18 PM To: info-ingres@cariboulake.com Subject: [Info-ingres] Re: What do you use VDBA for? "Steve McElhinney" <stevem@141.com> wrote in message news:1127468079.588035.180710@g14g2000cwa.googlegroups.com... > I was wondering what real-world uses there are for visual DBA? I can say with considerable confidence that practically nobody uses it in the real world. It is nice for displaying QEPs and that is all. Unfortunately that is something that is of more use to programmers than DBAs and programmers can't get the...

Re: Save and Re-Use a File Equation
Jay, Set your parameters for the file equation in a var and then use that var each time you want the same settings... :setvar myfeq ";dev=myprinter,#,#....." :file apprint=reporta!myfeq .... .... .... :file apprint=reportc!myfeq duane > -----Original Message----- > From: owner-hp3000-l@RAVEN.UTC.EDU > [mailto:owner-hp3000-l@RAVEN.UTC.EDU] On Behalf Of > reid_e_baxter@bankone.com > Sent: Monday, April 04, 2005 10:13 AM > To: Jay Willis > Cc: HP3000-L@RAVEN.UTC.EDU > Subject: RE: Re: [HP3000-L] Save and Re-Use a File Equation > &g...

RE: Using Python with SyBase
Widom wrote: > Does anybody expirience Python for writing user front-end screens for > SyBase-Anyware databse ? > Where can I found more information how handle SyBase=20 > SQL-Anyware from Python > ? I used to have a Sybase application around here somewhere....ah. Looks like I used ODBC. :) Look for dbi and odbc modules. Robert Brewer MIS Amor Ministries fumanchu@amor.org ...

Re: Re: Re: Re: No future for DB2
Well, IDS 10 + XPS 9 as open source = Astonishing cool !! J. -----Original Message----- From: "Obnoxio The Clown" <obnoxio@serendipita.com> To: "Jean Sagi" <jeansagi@myrealbox.com> Date: Wed, 27 Jul 2005 22:00:31 +0100 (BST) Subject: Re: Re: Re: No future for DB2 Jean Sagi said: > > Online 5. as open source = Quite cool. But hugely impractical, as it would reveal far too much about IDS to the competition. -- Bye now, Obnoxio "C'est pas parce qu'on n'a rien � dire qu'il faut fermer sa gueule" - Coluche A smile is a gift that is free to the giver and precious to the recipient. But giving someone the finger is free too, and I find it more personal and sincere. Jean Sagi jeansagi@myrealbox.com jeansagi@gmail.com sending to informix-list ...

RE : Re: RE : Re: copulas and SAS
Thanks, I appreciate your comments,I understand that copula is not the appropriate tool to use, what will be the alternative ? Adel David L Cassell <davidlcassell@MSN.COM> a �crit : joewhitehurst@GMAIL.COM replied: > >Adel, > >You may find the following artilce interesting. [article by Thomas Mikosch not copied] This is a really good article, and a really useful point to make. But 55K is a lot of article to copy. Would it have been easier to point to a URL? The people who read SAS-L as a digest and the people who have slow connections are probably not overly thrilled...

Re: Re: Re: Radio Re: Shack Re: TRP-100 Re: Printer Re:
> Also, trim your replies. Leaving a few pages of original text just so > you can add your few lines at the bottom is just insane. > > g. > > -- > Proud owner of F-15C 80-0007 > http://www.f15sim.com - The only one of its kind. > http://www.diy-cockpits.org/coll - Go Collimated or Go Home. > Some people collect things for a hobby. Geeks collect hobbies. > > ScarletDME - The red hot Data Management Environment > A Multi-Value database for the masses, not the classes. > http://scarlet.deltasoft.com - Get it _today_! > --- Synchrone...

Re: [dhcwg] Re: DHCID and the use of MD5 [Re: Last Call:'Resolution ofFQDN Conflicts among DHCP Clients' to ProposedStandard]
> > This technique has been in use for years by implementations > > using TXT records because we've been unable to get the DHCID > > RR approved. > > OK so why are you proposing a new protocol rather than writing a > description of the protocols that are already in use? > > Correctly prefixed TXT records work just as well as new RRs and are > completely compatible with the deployed infrastructure. If you attempt > to cut new DNS RRs you will hit the problem that your proposal is now > dependent on deployment of a new infrastructure...

Web resources about - Using re.VERBOSE, and re-using components of regex? - comp.lang.python

Component - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

DPRK may have tested components of hydrogen bomb
DPRK may have tested components of hydrogen bomb

Waterproof components listed for Galaxy S7 on import tracking site
... at least water-resistant – rumors are starting to look increasingly solid. Import tracking site Zauba has revealed several “waterproof” components ...

Minecraft: Pocket Edition receives a new update with additional Redstone components
... fare like elevators. It definitely opens up the possibilities in the already multi-faceted game. The update adds other Redstone components ...

The hidden story of one of the iPhone’s most important components
... it’s probably the software and the ecosystem around it that stand out. But to make all this software magic possible possible, there’s one component ...

A fundamental component of the 'Making a Murderer' mystery relies on a single test — here’s what we know ...
The moment viewers think the tide could change in the trial of Steven Avery comes with the discovery of a hole in a tube. Avery, the subject ...

Auto Expo 2016 - The Motor Show & Components, Delhi,India - Business Standard
Get latest Cars, bikes, auto vehicle launches and News on The Motor & Components Show from Auto Expo 2016. Get exclusive updates for car, bike ...

There's more to Lent than fasting: a look at the 3 components of Lenten observance
If you only paid attention to the mainstream media, you would be forgiven for thinking that Lent is all about fasting in response to Jesus' temptation ...

Iran exports heavy water, a nuclear reactor component, to US
TEHRAN, Iran (AP) — Iran's semi-official ISNA news agency says the country has exported heavy water, a key component for one kind of nuclear ...

Component maker Mag.Layers reports decreased revenues for February
Passive component maker Mag.Layers Scientific-Technics has reported revenues of NT$164.67 million (US$5.06 million) for February, down 39.4% ...

Resources last updated: 3/10/2016 6:25:44 AM