How do I escape a string as a regular expression?

Everything else that doesn't fall into one of the other PB categories.
riku22
New User
New User
Posts: 8
Joined: Wed Feb 09, 2022 3:20 am

How do I escape a string as a regular expression?

Post 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.
User avatar
Demivec
Addict
Addict
Posts: 4270
Joined: Mon Jul 25, 2005 3:51 pm
Location: Utah, USA

Re: How do I escape a string as a regular expression?

Post by Demivec »

You question is a little vague, at least to me.

Perhaps this: https://www.purebasic.com/documentation/string/escapestring.html
riku22
New User
New User
Posts: 8
Joined: Wed Feb 09, 2022 3:20 am

Re: How do I escape a string as a regular expression?

Post 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\+".
Marc56us
Addict
Addict
Posts: 1600
Joined: Sat Feb 08, 2014 3:26 pm

Re: How do I escape a string as a regular expression?

Post 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.
:wink:
riku22
New User
New User
Posts: 8
Joined: Wed Feb 09, 2022 3:20 am

Re: How do I escape a string as a regular expression?

Post 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.
AZJIO
Addict
Addict
Posts: 2191
Joined: Sun May 14, 2017 1:48 am

Re: How do I escape a string as a regular expression?

Post by AZJIO »

find: [][{}()*+?.\\^$|=<>#]
replace: \\$0

\Q my_regexp \E

https://www.purebasic.fr/english/viewtopic.php?t=78070
riku22
New User
New User
Posts: 8
Joined: Wed Feb 09, 2022 3:20 am

Re: How do I escape a string as a regular expression?

Post by riku22 »

Hello.

Thank you very much.
I was able to achieve what I wanted to do.

Sincerely.
Post Reply