Hack Forums
[Python] REGEX Simple Expression Question - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Python] REGEX Simple Expression Question (/showthread.php?tid=5701978)



REGEX Simple Expression Question - TheWarOwl - Aug 23, 2017

Just a quick curious question. Before I knew regex I did some research on how I can pull information from the source of webpages and found that people would use:

PHP Code

<?php 
somestuff
(.*?)somemorestuff 

Which was used to pull all information between two sets of strings.

Now that I'm learning regex I know that the "?" refers to a character being "optional". So if I have:

PHP Code

<?php 
abc
ac 

And I want to select both lines I'd use:

PHP Code

<?php 
ab
?c 

This leads me to my actual question... if I want to select everything between "abc" in this string:

PHP Code

<?php 
abc dsfljkdslkfjdslfkj abc 

What's wrong with

PHP Code

<?php 
abc
(.*)abc 

Why would I need "?" in the expression? This makes zero sense to me.


* - Vanagander - Aug 23, 2017

.* will match as much as possible and is Greedy, while .*? will match only as much as is needed because the ? changes Greedy to Stingy.

"foo.*bar" This will match "food is under the bar in the bar" - Greedy
"foo.*?bar" This will match "food is under the bar" -

Try to put in abc somewhere in your string and test the difference
(abc dsfljkdsabclkfjdslfkj abc)

Hoppfully you understood me, it's way too early to think straight..


* - TheWarOwl - Aug 23, 2017

NEVERMIND:

If I had another "abc" in the middle of my data ".*" means match all of any character. So this would only stop at the last occurrence of my line.

Adding the ".*?" in simple terms means match all of any character and "not be greedy". So the first occurrence makes regex stop there instead of the new line.


(Aug 23, 2017 10:11 PM)Vanagander Wrote:  .* will match as much as possible and is Greedy, while .*? will match only as much as is needed because the ? changes Greedy to Stingy.

"foo.*bar" This will match "food is under the bar in the bar" - Greedy
"foo.*?bar" This will match "food is under the bar" -

Try to put in abc somewhere in your string and test the difference
(abc dsfljkdsabclkfjdslfkj abc)

Hoppfully you understood me, it's way too early to think straight..

You got here right when I figure it out lol.

But thank you for your answer! I looked at your response and it did clarify a little more for me. Thank you 🤝