|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Need a little help with regex
This may seem like a daft question but how can I alter a string so as to only leave letters and numbers, i.e. strip out all punctuation etc.
I currently use the following: Code:
$search_terms =~ s/\'//g; $search_terms =~ s/\"//g; $search_terms =~ s/\£//g; ... as I don't know any better, can someone please help me out and show me something better. TIA |
|
#2
|
||||
|
||||
|
Yeah, regexes are a pain to figure out.
A better way to think about them is what you want to leave in, and not what you want to take out. . .Otherwise you'd need to create a regex for every invalid character- a pain to say the least. So, Code:
$search_terms =~ s/[^\w\d\s]//g; This takes anything that isn't whitespace, a digit or a valid perl identifier (which includes a-z _ and some other characters) and nixes it. This has the advantage of working with multiple languages if you "use locale;". If you truly want to restrict it to only A-Z, 0-9 and whitespace, then use Code:
# the a-zA-Z construct is faster than using the /i switch. $search_terms =~ s/[^a-zA-Z\d\s]//g; Look into "character classes" in regexes for this type of matching. |
|
#3
|
|||
|
|||
|
That's brilliant, thanks a lot.
I knew there must be an easier way to do it than taking out all the letters individually, just didn't know how to reverse it, cheers |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Perl Programming > Need a little help with regex |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|