Page 1 of 1
How do I escape a string as a regular expression?
Posted: Wed Feb 09, 2022 3:36 am
by riku22
Hello.
How do I escape a string as a regular expression?
For example, converting "\d+" to "\\d\+".
In languages like Python, there are dedicated functions, how do I do that in PureBasic?
Any suggestions on how to do this would be appreciated.
Sincerely.
Re: How do I escape a string as a regular expression?
Posted: Wed Feb 09, 2022 4:14 am
by Demivec
Re: How do I escape a string as a regular expression?
Posted: Wed Feb 09, 2022 4:29 am
by riku22
Hello.
I apologize for the vagueness of my question.
I also found "EscapeString", but it can't escape a string used as a regular expression pattern.
For example, if you want to specify the string "\d+" itself as a regular expression pattern, you need to escape it as "\\d\+".
Re: How do I escape a string as a regular expression?
Posted: Wed Feb 09, 2022 7:49 am
by Marc56us
riku22 wrote: Wed Feb 09, 2022 3:36 am
How do I escape a string as a regular expression?
For example, converting "\d+" to "\\d\+".
In languages like Python, there are dedicated functions, how do I do that in PureBasic?
Hello,
Prefix string with au tilde (~) tells PB to handle escape characters.
Code: Select all
RegEx$ = ~"\\d+" ; not "\\d\+""
Debug RegEx$ ; show \d+
; With RegEx
CreateRegularExpression(0, ~"\\d+")
PS. You can use it even outside regular expressions
Code: Select all
A$ = ~"\"Hello World\""
Debug A$ ; show "Hello World"
It's easier than using #DQUOTE$ or concatenating chains (ie: Chr(34)) and it's Win/Linux/Mac compatible.

Re: How do I escape a string as a regular expression?
Posted: Wed Feb 09, 2022 12:30 pm
by riku22
Hello.
Sorry, that's not what I want to implement.
I want to perform a function similar to Python's
re.escape function or PHP's
preg_quote function.
Re: How do I escape a string as a regular expression?
Posted: Wed Feb 09, 2022 3:07 pm
by AZJIO
find: [][{}()*+?.\\^$|=<>#]
replace: \\$0
\Q my_regexp \E
https://www.purebasic.fr/english/viewtopic.php?t=78070
Re: How do I escape a string as a regular expression?
Posted: Thu Feb 10, 2022 5:57 am
by riku22
Hello.
Thank you very much.
I was able to achieve what I wanted to do.
Sincerely.