locked
string generation using regex (regular expression) RRS feed

  • Question

  • i have to generate a string based upon a regular expression provided as input.

     There is a System.Text.RegularExpressions.Regex class in .net but i could not find any API to generate string using a Regex object.

    Can any suggest how  can i generate a string using regular expression in C#? 

    Tuesday, September 19, 2006 11:19 AM

Answers

  • If you have a pattern in text that can be identified, then one can use Regex to replace items from within the string. See Example

    Example

    string textLine = "Hello world. <br>";

    string regEx = "<br>";

    string replacement = "<br/>";

    string result =

    Regex.Replace(textLine, regEx, replacement, RegexOptions.IgnoreCase);

    The <br> will be replaced with </br>.

    Now there is more power and flexibility in the Reg Ex language. One doesn't have to do replace with regex...one can extract substrings, see this post Help on Creating Regular Expression for an example. The onus is on you to determine what patterns you have and how the output using RegEx is feasable.

    Monday, October 2, 2006 5:50 PM
    Moderator

All replies

  • How do you mean, "generate a string"? Regular expressions are for checking and replacing text in existing strings.
    Tuesday, September 19, 2006 11:42 AM
  • I am trying to build a data manager (for data driving tests)  which could generate a string based on patterns given as input. i thought using regular expressions for patterns would be suitable. Can you suggest a way to do this?
    Tuesday, September 19, 2006 12:32 PM
  • If you have a pattern in text that can be identified, then one can use Regex to replace items from within the string. See Example

    Example

    string textLine = "Hello world. <br>";

    string regEx = "<br>";

    string replacement = "<br/>";

    string result =

    Regex.Replace(textLine, regEx, replacement, RegexOptions.IgnoreCase);

    The <br> will be replaced with </br>.

    Now there is more power and flexibility in the Reg Ex language. One doesn't have to do replace with regex...one can extract substrings, see this post Help on Creating Regular Expression for an example. The onus is on you to determine what patterns you have and how the output using RegEx is feasable.

    Monday, October 2, 2006 5:50 PM
    Moderator