Regex: elimina la expresión regular coincidente
Frecuentes
Visto 458 equipos
0
How to remove applied regular expression from string and get original string back.
tengo cuerda
12345679
and after applying regular expression i got string
"123-456+789"
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
Regex.IsMatch()
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.InitializeComponent();
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.
}
2 Respuestas
1
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;
break;
}
contestado el 28 de mayo de 14 a las 14:05
0
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 :
- Keep a copy of original.
- 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 c# regex or haz tu propia pregunta.
And can't you use regex on a COPY of your original string? ;) - Kamil T
Save a copy of the original? - Chris Hinton
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? - Nzall