Regex: elimina la expresión regular coincidente

How to remove applied regular expression from string and get original string back.

tengo cuerda


and after applying regular expression i got string


In my code i have different types of regular expression , i want to find which regular expression matches to current string and convert it back to original format

I can find regular expression using


but how to get original string ?

here is piece of code

     /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
          this.patientIdPattern = @"^(\d{3})(\d{3})(\d{3})";
          this.patientIdReplacement = "$1-$2+$3";

        /// <summary>
        /// Handles the OnLostFocus event of the UIElement control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void UIElement_OnLostFocus(object sender, RoutedEventArgs e)
          string formatted = Regex.Replace(textBox.Text, this.patientIdPattern, this.patientIdReplacement);
          lblFormatted.Content = formatted;

public void GetOriginalString(string formattedString)
//// Now here i want to convert formatted string back to original string.

preguntado el 28 de mayo de 14 a las 14:05

And can't you use regex on a COPY of your original string? ;) -

Save a copy of the original? -

Could you give an example of 1) the string; 2) the regex that matches this string; 3) the code that applies this regex to the string and 4) the result of the regex? -

2 Respuestas

The full match is always at index 0 of the MatchCollection devuelto por Regex.Matches.

Prueba esto:

string fullMatch = "";

var matchCollection = Regex.Matches(originalText, regex);

foreach(var match in matchCollection)
   fullMatch = match.Groups[0].Value;

contestado el 28 de mayo de 14 a las 14:05

There is no way to ask Regex to return the original input, other than keep a copy of it by yourself. Since, depend on how you use it, Regex.Replace may be an one way only transformation. Your options are :

  1. Keep a copy of original.
  2. Handcraft some way to revert the transformation. This cannot be done por arte de magia.
Regex.Replace("123-456+789", @"^(\d{3})\-(\d{3})\+(\d{3})", "$1$2$3")

contestado el 28 de mayo de 14 a las 15:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.