CodeIgniter Forums
Regex help! - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Regex help! (/showthread.php?tid=7099)



Regex help! - El Forum - 03-25-2008

[eluser]Ryuuzaki92[/eluser]
hi, i want a regexp to detect

is_admin => admin
is_admin_or_lower => admin, lower
is_admin_or_higher => admin, higher

im currently using this but it doesnt detect the _or_lower|higher

Code:
/^is_(.+)(_or_(higher|lower))?$/



Regex help! - El Forum - 03-25-2008

[eluser]xwero[/eluser]
have you tried
Code:
/^is_(.+)(_or_higher|_or_lower)?$/



Regex help! - El Forum - 03-25-2008

[eluser]Doosje[/eluser]
Try,
Code:
/^is_([A-z]+)(\_or\_(higher|lower))?$/



Regex help! - El Forum - 03-25-2008

[eluser]Ryuuzaki92[/eluser]
thanks guys.
this works:
Code:
'/^is_([a-z]+)(_or_(higher|lower))?$/'



Regex help! - El Forum - 03-25-2008

[eluser]xwero[/eluser]
Doosje the underscore isn't a metacharacter AFAIK so i don't think that is the problem. I tested the regex and the problem is with the (.+) it catches admin_or_higher. So the regex will have to be something like
Code:
/^is_([a-zA-Z]+)_or_?(higher|lower)?$/
I've put the _or_ outside the backets because i think it doesn't matter. If it's inside the barkets you get following result
- admin
-_or_higher
- higher

edit : it's monday for all of us Smile


Regex help! - El Forum - 03-25-2008

[eluser]Doosje[/eluser]
xwero, you're right ..
but .. i make a llittle adustment .. bucase _or_ alsso needs to be in catched
Code:
/^is_([a-zA-Z]+)(_or_(higher|lower))?$/

(at least, if i'm reading right but it's early for me .. only awake for half an hour)


Regex help! - El Forum - 03-25-2008

[eluser]m4rw3r[/eluser]
Try making (.+) to a non greedy expression: (.+?)
Then you don't have to restrict the characters in the username


Regex help! - El Forum - 03-26-2008

[eluser]Ryuuzaki92[/eluser]
[quote author="m4rw3r" date="1206484114"]Try making (.+) to a non greedy expression: (.+?)
Then you don't have to restrict the characters in the username[/quote]

oo great tip! but can you explain to me why is it different?

im really a noob @ regexp =(


Regex help! - El Forum - 03-26-2008

[eluser]xwero[/eluser]
the question mark is used for string that can be there or not like
Code:
/_or_?(higher|lower)?/
when used after + or * the catching of the group is less aggressive.

Another good to know option with the question mark is ?: before a group like
Code:
/(?:[a-z]*)_(higher|lower)/
$1 will be either higher or lower and not the first group. If you use regex to match something without the need of returning use that syntax for better performance.

If you want a site with information about regex go to http://www.regular-expressions.info/