Showing posts with label Regular expression. Show all posts
Showing posts with label Regular expression. Show all posts

Thursday, 15 August 2013

Validate string with a regular expression

Regular expression is really an amazing function in string processing. In this article, I will introduce a popular case using regular expression to solve validate string with muli-conditions: validate password strength.

Requirements
  • program language must support regular expression with look lookahead assertion.

These are the rules
  • The password length must be greater than or equal to 7 characters
  • The password must contain one or more uppercase characters
  • The password must contain one or more lowercase characters
  • The password must contain at least one numeric character.

And this is the answer
(?=^.{7,}$)(?=.*\d)(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$
You can see colors and very easy to know. The end to finish a regex (all of first statement is only condition, must have main body and check that end with end of line (with multiline mode) or end of string (with singleline mode).

Test online with


Wednesday, 31 July 2013

Tools, tips support regular expression in Python

To get full information of Regex in python, please read this link
http://docs.python.org/2/library/re.html

But to read and know all and practice immediately, this is really hard. In this article, I will share you some powerful regular expression tools.

Kodos:

Kodos is a free, opensource software, cross platform. With this software, we can try regular expression with many options, new version of it support replace and generates to sample codes.


Pythonregex
Homepage: http://www.pythonregex.com/

Like Kodos but it generates code more details and measure runtime like this:
>>> regex = re.compile("(?P<key>\w*?)=(?P<value>\w*?)\s|$")
>>> r = regex.search(string)
>>> r
<_sre.SRE_Match object at 0x53bb4f400b615b08>
>>> regex.match(string)
<_sre.SRE_Match object at 0x53bb4f400b615880>

# List the groups found
>>> r.groups()
(u'color', u'fsck')

# List the named dictionary objects found
>>> r.groupdict()
{u'key': u'color', u'value': u'fsck'}

# Run findall
>>> regex.findall(string)
[(u'color', u'fsck'), (u'animal', u'aasvogel'), (u'vegetable', u'rutabaga'), (u'', u'')]

# Run timeit test
>>> setup = ur"import re; regex =re.compile("(?P<key>\w*?)=(?P<value>\w*?)\s|$");string="" ...
>>> t = timeit.Timer('regex.search(string)',setup)
>>> t.timeit(10000)
0.0131378173828