Home > Software design >  Regex only letters except set of numbers
Regex only letters except set of numbers

Time:06-24

I'm using Replace(@"[^a-zA-Z] ", ""); leave only letters, but I have a set of numbers or characters that I want to keep as well, ex: 122456 and 112466. But I'm having trouble leaving it only if it's this sequence:

ex input:

abc 1239 asm122456000

I want to:

abscasm122456

tried this: ([^a-zA-Z]) |(?!122456)

CodePudding user response:

My answer doesn't applying Replace(), but achieves a similar result:

(?:[a-zA-Z] |\d{6})

which captures the group (non-capturing group) with the alphabetic character(s) or a set of digits with 6 occurrences.

Regex 101 & Test Result


Join all the matching values into a single string.

using System.Linq;

Regex regex = new Regex("(?:[a-zA-Z] |\\d{6})");
string input = "abc 1239 asm12245600";
string output = "";

var matches = regex.Matches(input);
if (matches.Count > 0)          
    output = String.Join("", matches.Select(x => x.Value));

Sample .NET Fiddle

CodePudding user response:

Alternate way,

using .Split() and .All(),

string input = "abc 1239 asm122456000";
string output = string.Join("", input.Split().Where(x => !x.All(char.IsDigit)));

.NET Fiddle

  • Related