0

Is there any way to construct a regex which will be treated as only literal values, and stop processing it as a regex pattern? e.g. can I prefix or wrap it with some special sequence?

I'm using software based on the re2 library / syntax. I would like to prevent it from treating an entire string as a regex.

I tried using the comment syntax (?#text), but the re2 documentation states this is not supported and that seems to be the case.


Background:

I am working with an application that embeds re2 and uses it for string processing. (Happens to be EnergyPlus). As far as I can tell, it will always process certain strings assuming they follow regex syntax. There is no way I can find to tell it not to do that.

We have some cases where user-entered values have to be escaped to prevent this interpretation. For example, we need to replace ? in any of these strings with \? to prevent an error. We could do this for all the special chars in re2 but it would just be simpler if we could treat the entire string as not a regex pattern.

The re2 docs on https://github.com/google/re2/wiki/Syntax only mention escaping individual chars.

If it matters the strings originate from C# code, though I don't think that is very significant.

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
  • Does this answer your question? [What is the purpose of Regex.Escape?](https://stackoverflow.com/questions/7177771/what-is-the-purpose-of-regex-escape) – AdrianHHH Mar 28 '23 at 20:16
  • @AdrianHHH thanks that actually will be useful assuming I end up escaping all the regex syntactical characters. But I don't think its quite a duplicate in the sense that *ideally* I'd still like to find a way to tell it to just treat the entire string as a non-regex to begin with. – StayOnTarget Mar 28 '23 at 21:44
  • I think you need to clarify the question and show code of how you want to use the strings that are to be used as Regexs and those that are not. – AdrianHHH Mar 29 '23 at 08:36
  • I don't want any of them to be used as regex. – StayOnTarget Mar 29 '23 at 11:09
  • So just use `Regex.Escape(the_entire_input_text)` in your C# code. – AdrianHHH Mar 29 '23 at 19:19
  • @AdrianHHH that may work but it assumes that the regex syntax built into .net is the same as the RE2 syntax used by the library I'm working with. I'm not yet sure of that. – StayOnTarget Mar 29 '23 at 19:24

0 Answers0