Are regular expressions the same in every programming language?

Viewed 2742

I am a python user looking to learn regular expressions and I have just a good good course on Udemy that seems to be OK. However it is neither a python course nor a python regular expression course.

Are regular expressions the same on any programming language ?

I mean would they be the same and use the exact same syntax I would be using with the re package in python ?

2 Answers

there are variations on them...

this site will give you a way to test your expression for some common languages (including python)...

https://regex101.com/

There are significant differences both large and subtle between implementations.

According to the (2.7) regex howto, Python's re module was based on Perl regular expressions. The regular expression syntax is almost the same. The usage in Perl is quite different; more compact (or more unreadable, depending on your views :-).

Also keep in mind that there are differences in regular expressions between Python 2 and 3, depending on which flags are used. Simplifying somewhat you could say that out of the box, Python 2 regexes handle ASCII strings while Python 3 handle unicode strings.

In Python regular expressions, the * and + qualifiers are greedy, that is they match as much text as possible. That makes for results that are not intuitive. For example, suppose you want to search for text between angle brackets. You might think that <.*> might do that. But observe:

In [1]: import re

In [2]: re.findall('<.*>', '<a> <b> <c>')
Out[2]: ['<a> <b> <c>']

You have to add a ? to make them non-greedy.

In [3]: re.findall('<.*?>', '<a> <b> <c>')
Out[3]: ['<a>', '<b>', '<c>']

To be explicit, you'd have to look for anything but the end character.

In [4]: re.findall('<[^>]*>', '<a> <b> <c>')
Out[4]: ['<a>', '<b>', '<c>']

UNIX-like systems such as Linux and *BSD generally support POSIX regular expressions in many utilities. Those come in two flavors, basic and extended. Basic POSIX regular expressions do not support the branching metacharacter |.

Related