What is a regular expression in python tutorial?
A regular expression is a special
sequence of characters that helps you match or find other strings or sets of
strings, using a specialized syntax held in a pattern. Regular expressions are
widely used in UNIX world.
Regular expression
patterns are compiled into a series of bytecodes which are then executed by a
matching engine written in C. For advanced use, it may be necessary to pay
careful attention to how the engine will execute a given RE, and write the RE
in a certain way in order to produce bytecode that runs faster. Optimization
isn’t covered in this document, because it requires that you have a good
understanding of the matching engine’s internals.
The regular
expression language is relatively small and restricted, so not all possible
string processing tasks can be done using regular expressions. There are also
tasks that can be
done with regular expressions, but the expressions turn out to be very
complicated. In these cases, you may be better off writing Python code to do
the processing; while Python code will be slower than an elaborate regular
expression, it will also probably be more understandable.
A step-by-step example will make this
more obvious. Let’s consider the expression a[bcd]*b. This matches the letter 'a', zero or more
letters from the class [bcd], and finally ends
with a 'b'. Now imagine matching this RE against the
string 'abcbd'.
Step
|
Matched
|
Explanation
|
1
|
a
|
The a in the RE
matches.
|
2
|
abcbd
|
The engine matches [bcd]*, going as far as
it can, which is to the end of the string.
|
3
|
Failure
|
The engine tries to match b, but the current
position is at the end of the string, so it fails.
|
4
|
abcb
|
Back up, so that [bcd]* matches one
less character.
|
5
|
Failure
|
Try b again, but
the current position is at the last character, which is a 'd'.
|
6
|
abc
|
Back up again, so that [bcd]* is only
matching bc.
|
6
|
abcb
|
Try b again. This
time the character at the current position is 'b', so it succeeds.
|
Python Interview Questions and Answers
What is the regular expression?
What is a regular expression in Python?
What is regular expression in computer science?
What is a regular expression in Javascript?
What is the regular expression for?
What is a question mark in regex?
What is an argument to a function in Python?
What is def in Python?
What is the meaning of DEF in Python?
What is the definition of DEF in Python?
What does def mean at gas stations?
Is DEF fluid made from pig urine?
Is DEF fluid made from urine?
0 comments:
Post a Comment