Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple groups in one regex?

Tags:

c#

.net

regex

I'm trying to match two groups in the same Regex object in .NET, so I can process them separately; I'd hate to instantiate many objects for every individual expression. Basically, I'd like to insert an underscore before a period and a dash before an exclamation point. Now, I know I can use punctuation constructs, but I'd like to use each group as an individual expression.

Here's a variation of the million ways I've tried:

using System.Text.RegularExpressions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
    {
    public partial class Form1 : Form
        {
        public Form1()
            {
            InitializeComponent();
            var rule = new Regex(@"(\.)(\!)", RegexOptions.Compiled);
            var myText = "string. will! way. water! test. quiz! short. long!";
            richTextBox1.Text = rule.Replace(rule.Replace(myText, "_$1"), "-$2");
            }
        }
    }

Thanks so much in advance.

like image 450
Jesus Kevin Morales Avatar asked Jan 11 '23 01:01

Jesus Kevin Morales


2 Answers

This should work. It uses a Lamba, but if you want more control you can break it out into a function. The Match delegate can be either. Basically the regex engine calls your delegate with each match, passing in the matched value, so you can decide what to do with it on the fly.

Regex.Replace("Test a. b!", @"([.!])",
       (m) => { return m.Value == "." ? "_." : "-!"; }
    );
like image 154
codenheim Avatar answered Jan 20 '23 16:01

codenheim


The answer to your question is: You can't use groups to do that. Multiple replacement strings just aren't supported, and neither is putting the replacement string into the match itself.

You can use a regex and a match evaluator to do what you want, as the other answers show, but groups play no part in that.

The solution to your problem is: Use plain string replacements. You're not doing anything complicated enough to require a regex.

var myText = "string. will! way. water! test. quiz! short. long!";
richTextBox1.Text = myText.Replace(".", "_.").Replace("!", "-!");
like image 32
Kendall Frey Avatar answered Jan 20 '23 15:01

Kendall Frey