Reputation: 1
How to remove applied regular expression from string and get original string back.
i have string
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.
}
Upvotes: 0
Views: 556
Reputation: 14477
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 :
Regex.Replace("123-456+789", @"^(\d{3})\-(\d{3})\+(\d{3})", "$1$2$3")
Upvotes: 0
Reputation: 8444
The full match is always at index 0 of the MatchCollection
returned by Regex.Matches
.
Try this:
string fullMatch = "";
var matchCollection = Regex.Matches(originalText, regex);
foreach(var match in matchCollection)
{
fullMatch = match.Groups[0].Value;
break;
}
Upvotes: 1