Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Escaping regular text string for use in Reg Ex???
Message
From
12/04/2011 05:46:21
 
 
To
12/04/2011 05:32:47
General information
Forum:
Visual FoxPro
Category:
Coding, syntax & commands
Environment versions
Visual FoxPro:
VFP 9 SP2
Database:
Visual FoxPro
Miscellaneous
Thread ID:
01504973
Message ID:
01506977
Views:
50
>>I’m working on a re-write of the VFP app GoFish (search and replace tool). One thing I am doing with the new version is that internally I’m using Regular Expressions to perform the search rather than the original way it worked which was that it just used the $ function to look for a string match.
>>
>>So the user will enter a search string which could very likely contain some characters that are reserved characters in regular expressions. (i.e. ^[]\{}.,;+-$ etc.) I need to escape those characters in the user input so the reg ex search will work properly.
>>
>>There are lots of way one could iterate over the input string to escape all the special characters, and I’m sure there are some trick one must figure out to do it correctly, so, before I re-invent the wheel here, I’m asking around to see if anyone already has the code to do this.
>>
>>Anyone?
>
>
>
>You use regex to change the search string
>
>
>	local regexObj
>	local specialChars, specialCharsPattern, replacePattern
>	
>	local i
>	
>	specialChars = '\^$.[]()|{}*+?'
>	
>	replacePattern = '\$&' && or '\$1'
>	regexObj = createObject('VBScript.RegExp')
>	regexObj.IgnoreCase = false
>	regexObj.Global = true
>	
>	&& construct specialCharsPattern
>	specialCharsPattern = '('
>	
>	for i = 1 to len(m.specialChars)
>		specialCharsPattern = m.specialCharsPattern  + '\' + substr(m.specialChars, m.i, 1) + '|'
>	endfor
>	specialCharsPattern = left(m.specialCharsPattern, len(m.specialCharsPattern)-1) + ')'
>	
>	regexObj.Pattern = m.specialCharsPattern
>	
>	
>	&& examples
>	local inputSearchString, useSearchString
>	
>	inputSearchString = m.specialChars
>	useSearchString= regexObj.Replace(m.inputSearchString , m.replacePattern )
>	?'inputSearchString: ', m.inputSearchString
>	?'useSearchString: ', m.useSearchString
>	
>	
>	inputSearchString = 'a( $ )'
>	useSearchString= regexObj.Replace(m.inputSearchString , m.replacePattern )
>	?'inputSearchString: ', m.inputSearchString
>	?'useSearchString: ', m.useSearchString
>
More efficient to just do
specialChars = "(\\|\^|\$|\.|\[|\]|\(|\)|\||\{|\}|\*|\+|\?)"
and get rid of the for/endfor ?
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform