Use a Python regex to check a key:value;key:value; string is well-formed -


Handles the wire made from my Python program ID: value; Like pairs:

  s = "1: name; 2: second name; 3: one last name;"  

ID should always be numeric and final; It is optional I want to implement a regex which both checks that the string is well formed and splits for me.

I wrote it:

  & gt; & Gt; & Gt; Import re & gt; & Gt; & Gt; R = re.compile (r '([0-9] +): ([^:;] +) (?: | $) *')  

That sounds like Partition properly:

  & gt; & Gt; & Gt; ['1': 'name', '3': 'one last name', '2': 'alias'}  

What problem do I have to hold faulty stars Want to use Reggae? Is there a way to change it so that the following operations fail?

  & gt; & Gt; & Gt; R.match ("1: name; dummy: alias; 3: one last name;"> gt; & Gt; & Gt; R.match ("1: name; A2: alias; 3: one last name;")  

Thanks! Frank

You can display a match using a different regex which contains the $ end string , Which string for you

  & gt; & Gt; & Gt; Valid = re.compile (r '(([0-9] +): ([^:;] +) (?:; $) *) * $') & Gt; & Gt; & Gt; Validate.match ("1: name; 2: alias; 3: one last name;") & lt; _sre.SRE_Match object 0x02B132A0 & gt; & Gt; & Gt; & Gt; Validate.match ("1: name; dummy: second name; 3: one last name;") # none else & gt; & Gt; & Gt; Validate.match ("1: name; A2: alias; 3: one last name;") # There is no one too  

One way I use matching and search Can not think for verification with the same regex

Here's an explanation why you can not use the same regex for grouping and verification : < / P>

You must use the findall () to get an unknown number of groups using a mail object, only Program will not because it will not contain any number of variables group.

Therefore it is given regex r that you are using findall () function, R for a The single expression must match in a string with a variable number of expressions, but there is no way to use r in the same way as mail () calls Since R , only one expression matches the string number in the string, the content of the remainder of the string must be guaranteed Is impossible.


Comments

Popular posts from this blog

ios - How do I use CFArrayRef in Swift? -

eclipse plugin - Run java code error: Workspace is closed -

c - Error on building source code in VC 6 -