Using escape character with start pattern in regex in c #

Below is a sample email that I am using from the database:

2.2|[johnnyappleseed@example.com]

      

Each line is different and it may or may not be an email, but it always will. I am trying to use regular expressions to get information inside brackets. Below I am trying to use:

^\[\]$

      

Unfortunately, every time I try to use it, the expression doesn't match. I think the problem is with the use of escape characters, but I'm not sure. If that's not how I'm using escaping characters with this, or if I'm completely wrong, please let me know what should be in the current regex.

+3


source to share


2 answers


Next to yours ^.*\[(.*)\]$

:

  • ^

    start of line
  • .*

    nothing
  • \[

    parenthesis indicating the beginning of a letter
  • (.*)

    anything (email) like a capture group
  • \]

    square bracket indicating the end of the letter
  • $

    end of line


Note that your regex is missing parts .*

to match things between the [and] key characters.

+2


source


Your regex - ^\[\]$

- matches one line / line containing only []

, and you need to get the substring between square brackets somewhere else inside the larger line.

you can use

var rx = new Regex(@"(?<=\[)[^]]+");
Console.WriteLine(rx.Match(s).Value);

      

See demo regex



With (?<=\[)

we find the position after [

, and then we match any character that is not ]

, with [^]]+

.

Another, not regular way:

var s = "2.2|[johnnyappleseed@example.com]";
var ss = s.Split('|');
if (ss.GetLength(0) > 1)
{
    var last = ss[ss.GetLength(0)-1];
    if (last.Contains("[") && last.Contains("@")) // We assume there is an email
        Console.WriteLine(last.Trim(new[] {'[', ']'}));
}

      

See IDEONE demo of both approaches

+1


source







All Articles