Thứ Hai, 14 tháng 12, 2009

regular Expressions

A quick note about these two assertions, let's start with positive lookahead:

"Assert that the regex below can be matched, starting at this position".

Let's go with this little example:

Regex:
\s+\w+(?=\.)

This would mean, match a space between one and many times followed by a word character between one an many times only if there is a dot following the previous match:

Eg.
andy mypass ok orange..see what is going on

The matched text here would be orange (Because there was a dot after "orange", ah yes, and many spaces before).

Now, let's go with the other case, negative lookahead:
"Assert that it is impossible to match the regex below starting at this position".
The regex changes to
\s+\w+(?!\.)

Do you see the difference?. this should read now:

Match a space between one and many times followed by a word character between one and many times only if the following character is not a dot, so what is matched now using our previous example:


mypass (Because after "mypass" was a space)
ok (Same reason using the word "ok")
orang (Because after "orang" there is an e)
see (Because after "see" there is a space)
.... and so on

0 nhận xét:

Đăng nhận xét