繁体   English   中英

正则表达式-删除匹配的正则表达式

[英]Regex - Remove matched regular expression

如何从字符串中删除应用的正则表达式并获取原始字符串。

我有绳子

12345679

在应用正则表达式后,我得到了字符串

“123-456 + 789”

在我的代码中,我有不同类型的正则表达式,我想找到与当前字符串匹配的正则表达式并将其转换回原始格式

我可以使用找到正则表达式

Regex.IsMatch() 

但是如何获取原始字符串?

这是一段代码

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

完全匹配始终位于MatchCollection返回的Regex.Matches索引0 Regex.Matches

尝试这个:

string fullMatch = "";

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

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

除了自己保留副本之外,没有其他方法可以要求Regex返回原始输入。 因为,取决于您的使用方式, Regex.Replace可能是仅一种方式的转换。 您的选择是:

  1. 保留原件的副本。
  2. 手工制作一些方法来还原转换。 这不可能神奇地做到。
Regex.Replace("123-456+789", @"^(\d{3})\-(\d{3})\+(\d{3})", "$1$2$3")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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