简体   繁体   中英

Regex - Remove matched regular expression

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.
}

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;
}

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 magically .
Regex.Replace("123-456+789", @"^(\d{3})\-(\d{3})\+(\d{3})", "$1$2$3")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM