Remove characters that do not start with numbers with c# Regex.Replace

Asked 1 years ago, Updated 1 years ago, 44 views

It's my first time using c# Regex.Replace, so I'm not sure.

For example, a = ",123 asdf,456ghjk,zxcv I only want to leave a = ",123 asdf,456ghjk" in Replace, but I don't know how to set the expression.

c# regex

2022-09-21 19:45

1 Answers

You can make the regex pattern into numbering + wording + commaing . I made a code to print out words that match.

The pattern is \d+.*?(?=,), and the regex here is *? and positive lookahead, which are Lazy quantifiers.

\d+ corresponds to number .*? corresponds to with the word. (Use the Lazy Quantifier) (?=,) corresponds to having a comma.

using System.Text.RegularExpressions;

public class Hello1 {
    public static void Main() {
       string input = ",123 asdf,456 ghjk,zxcv";
       Regex regex = new Regex(@"\d+.*?(?=,)");
       Match m = regex.Match(input);
       while (m.Success)
       {
         System. Console.WriteLine("{0}:{1}", m.Index, m.Value);
         m = m.NextMatch();
     }
 }
}

If you can interpret English to some extent, we recommend the https://regex101.com/ site to use Regex.


2022-09-21 19:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.