By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,446 Members | 2,998 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,446 IT Pros & Developers. It's quick & easy.

Verbatim String or Regex Pattern from Input

P: n/a
Hi,

I'm having a tricky problem where I want to accept a regular expression
pattern from user input but can't get teh escape characters to be prcoessed
correctly. If I take the same pattern and declare it in code with a
preceeding @ character it works fine.

To get the pattern to work from teh suer all \ have to be escaped, e.g.
instead of \d a user would have to enter \\d.

Is there anyway to convert a normal string to a verbatim string or some
other way to get a string treated as a verbatim string by Regex?

Regards,

Aaron
Apr 1 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a


"Jon Skeet [C# MVP]" wrote:
Aaron <Aa***@discussions.microsoft.comwrote:
I'm having a tricky problem where I want to accept a regular expression
pattern from user input but can't get teh escape characters to be prcoessed
correctly. If I take the same pattern and declare it in code with a
preceeding @ character it works fine.

To get the pattern to work from teh suer all \ have to be escaped, e.g.
instead of \d a user would have to enter \\d.

Is there anyway to convert a normal string to a verbatim string or some
other way to get a string treated as a verbatim string by Regex?

"Verbatim string literal" is a strictly compile-time business - it's
only relevant in actual C# code.

Could you post a short but complete program which demonstrates the
problem?
An example of the problem would be:

1. Ask the user for some input to be used as a regular expression pattern:

Enter =\d+

2. Read it in and attempt to use it as a regex pattern.

string pattern = Console.Readline();
if(Regex.Match("12", pattern).Success)
{
Console.WriteLine("match");
}
else
{
Console.WriteLine("no match");
}

The output will be: no match.

3. If the user enters \\d+ the output will be: match.

Regards,

Aaron
Apr 1 '08 #2

P: n/a
On Tue, 1 Apr 2008 03:08:07 -0700, Aaron <Aa***@discussions.microsoft.com>
wrote:
>Hi,

I'm having a tricky problem where I want to accept a regular expression
pattern from user input but can't get teh escape characters to be prcoessed
correctly. If I take the same pattern and declare it in code with a
preceeding @ character it works fine.

To get the pattern to work from teh suer all \ have to be escaped, e.g.
instead of \d a user would have to enter \\d.

Is there anyway to convert a normal string to a verbatim string or some
other way to get a string treated as a verbatim string by Regex?

Regards,

Aaron
Hmm, is Regex.Escape what you are looking for?

Regards,
Gilles.

Apr 1 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.