gleam-lang / stdlib

🎁 Gleam's standard library
https://hexdocs.pm/gleam_stdlib/
Apache License 2.0
482 stars 169 forks source link

Add `regex.escape` #677

Open apainintheneck opened 2 months ago

apainintheneck commented 2 months ago

This would take a string and return a string with all regex-specific characters escaped so that it would match the literal string if compiled to a regex. It would be useful when you want to exactly match part of a string while partially matching other parts a string. I'm not sure how difficult this would be to add though because of the differences between JS and Erlang regex syntax.

fn escape(string: String) -> String

Related:

apainintheneck commented 2 months ago

Looking into things a bit further it seems like the Regex syntax for each platform might be similar enough in terms of matacharacter usage that this won't be a big lift. Even though the JS Regex Syntax seems to have more features if we escape common metacharacters (see the Erlang re docs) things might just work.

apainintheneck commented 2 months ago

From my testing, the following should work here.

https://github.com/apainintheneck/globlin/blob/bccfcd017491cb716a30fa7ce1c2e5ab7a915f7a/src/path_pattern.gleam#L221-L244