Python Regex vs PHP Regex

Not a competition, it is instead me trying to find why a certain regex works in one but not the other.


That's my Regex and I'm trying to run it on

Using Pythons regex I get nothing, using PHP I match it, below are the two calls I am making (just incase it's something to do with that). Essentially I am trying to work out why it works in PHP but not Python.

re.findall(regex, string)
preg_match_all($regex, $string, $matches);

Solution found, it was due to the way that I was iterating through the results, this regex turned them into groups and then it didn't want to print them out in the same way etc etc. Thank you all for your help, it's really appreciated.

Asked by: Aston436 | Posted: 28-01-2022

Answer 1

It works for me. You must be doing something wrong.

>>> re.match(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', '').groups()
('127', '255', '0', '0')

Don't forget to escape the regex using raw strings: r'regex_here' as stated in the Regex Howto

Answered by: Freddie644 | Posted: 01-03-2022

Answer 2

I would suggest that using a regex for decimal range validation is not necessarily the correct answer for this problem. This is far more readable:

def valid_ip(s):
    m = re.match(r"(\d+)\.(\d+)\.(\d+)\.(\d+)$", s)
    if m is None:
        return False
    parts = [int( for x in range(4)]
    if max(parts) > 255:
        return False
    return True

Answered by: Emma586 | Posted: 01-03-2022

Answer 3

Just because you can do it with regex, doesn't mean you should. It would be much better to write instructions like: split the string on the period, make sure each group is numeric and within a certain range of numbers.

If you want to use a regex, just verify that it kind of "looks like" an IP address, as with Greg's regex.

Answered by: Carlos744 | Posted: 01-03-2022

Answer 4

Without further details, I'd guess it's quote escaping of some kind. Both PHP and python's RegEX objects take strings as arguments. These strings will be escaped by the languge before being passed on to the RegEx engine.

I always using Python's "raw" string format when working with regular expressions. It ensure that "backslashes are not handled in any special way"


Answered by: Nicole579 | Posted: 01-03-2022

Answer 5

That regular expression matches here, no idea what you are doing wrong:

>>> import re
>>> x = re.compile(r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|'
... r'2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9]'
... r'[0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')
>>> x.match("")
<_sre.SRE_Match object at 0x5a8860>
>>> x.match("")
<_sre.SRE_Match object at 0x5a8910>
>>> x.match("")
<_sre.SRE_Match object at 0x5a8860>

Please note that preg_match translates to in Python and not re.match. re.match is for useful for lexing because it's anchored.

Answered by: Arthur684 | Posted: 01-03-2022

Answer 6

PHP uses 3 different flavors of regex, while python uses only one. I don't code in python, so I make no expert claims on how it uses REGEX. O'Reilly Mastering Regular Expressions is a great book, as most of their works are.

Answered by: Victoria389 | Posted: 01-03-2022

Similar questions

Ruby Regex vs Python Regex

Are there any real differences between Ruby regex and Python regex? I've been unable to find any differences in the two, but may have missed something.

Python regex to pick either regex A or regex B

I am trying to create a regex statement that will choose one regex or the other, for example: string = '123 Test String' pattern = r'( ?)([T](?P&lt;name1&gt;\w+))|([A](?P&lt;name2&gt;\w+))' m =, string) Basically, I want the Regex to pick one regex of the other.

Regex to python regex

I have a lot of file names with the pattern SURENAME__notalwaysmiddlename_firstnames_1230123Abc123-16x_notalways.pdf, e.g.: SMITH_John_001322Cde444-16v_HA.pdf FLORRICK-DOILE_Debora_Alicia_321333Gef213-16p.pdf ROBINSON-SMITH_Maria-Louise_321333Gef213-16p_GH.pdf My old regex was ([\w]*)_([\w-\w]+)\.\w+ but after sw...

python - Regex - Find 2 words or more using regex

Closed. This question needs to be more focused. It ...

python - regex in regex block

I've been trying parse a value in a block. Let me explain with an example. I have the following text : started xx xxxxxxx xxxxx xxxxxx xx xxxxxxxxx xxxxxxx xxxx xx xx xxx xxxxx xxxx xxxxxxxx xxxx xxxxxx found 9999 xxxxx xxxxx xxx xx xxxx xxxx xxxxxxxxxxx xxxxxxx xxx stored 9999 finished I'm trying to catch the value between "started" and "finished" I tried somethin...

python - Do not find a regex in another regex

I have a String that contains &quot;45+d6-1D10+47-12+1-7+106-100+100d100+151d258754&quot; I need to extract all the numbers that are not followed or preceded by the letter d or D. The matches i want here are : 45, 47, -12, 1, -7, 106, -100 My first wrong regex is ([\-]?(?!\d*[dD])(?!\d*[dD]\d)(\d+)) and it matches numbers after the d. Could you please help me...

regex - Python and "re"

A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed. After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix ...

regex - How to parse for tags with '+' in python

I'm getting a "nothing to repeat" error when I try to compile this: search = re.compile(r'([^a-zA-Z0-9])(%s)([^a-zA-Z0-9])' % '+test', re.I) The problem is the '+' sign. How should I handle that?

Slow regex in Python?

I'm trying to match these kinds of strings {} without matching any of these {} {} The regex I use is r"\{@csm.((?:[a-zA-Z0-9_]+\.?)+)\}" It gets dog slow if the string contains multiple matches. Why? It runs very fast if I take away the brace matching, like this

Regex From .NET to Python

I have a regular expression which works perfectly well (although I am sure it is weak) in .NET/C#: ((^|\s))(?&lt;tag&gt;\@(?&lt;tagname&gt;(\w|\+)+))(?($|\s|\.)) I am trying to move it over to Python, but I seem to be running into a formatting issue (invalid expression exception). It is a lame question/request, but I have been staring at this for a while, but nothing obvious is jum...

regex - How can I parse text in Python?

Sample Text: SUBJECT = 'NETHERLANDS MUSIC EPA' CONTENT = 'Michael Buble performs in Amsterdam Canadian singer Michael Buble performs during a concert in Amsterdam, The Netherlands, 30 October 2009. Buble released his new album entitled 'Crazy Love'. EPA/OLAF KRAAK ' Expected result: " NETHERLANDS MUSIC EPA | 36 before Michael Buble performs in Amsterdam Canadian singer ...

How to use ? and ?: and : in REGEX for Python?

I understand that * = "zero or more" ? = "zero or more" ...what's the difference? Also, ?: &lt;&lt; my book uses this, it says its a "subtlety" but I don't know what exactly these do!

python - In regex, what does [\w*] mean?

What does this regex mean? ^[\w*]$

python - regex in for loop

How do you use a regex with a for loop in Python example data abc 1 xyz 0 abc 2 xyz 1 abc 3 xyz 2 How do you write regex for something like below for i in range(1, 3): re.match(abc +i xyz +(i-1))

regex - How to read this file using Python?


python - Regex to Split 1st Colon

I have a time in ISO 8601 ( 2009-11-19T19:55:00 ) which is also paired with a name commence. I'm trying to parse this into two. I'm currently up to here: import re sColon = re.compile('[:]') aString = sColon.split("commence:2009-11-19T19:55:00") Obviously this returns: &...

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python