Regular expression for conditionally formatting a numeric string

Source question deleted


I am looking for a regular expression that will format a string containing special characters, characters and numbers into a string containing only numbers. There are special cases where it is not enough to replace all non-numeric characters with "" (empty).

1.) Zero in parentheses.

  • If there are only zeros in the bracket (0), they should be removed if this is the first pair of brackets. (The second pair of brackets containing only zeros should not be deleted)

2.) Leading zero.

  • All leading zeros must be removed (without parentheses)

Examples of better understanding:

  • 123 (0) 123 would be 123123 (zero removed)
  • (0) 123 -123 would be 123123(zero and all other non-numeric characters removed)
  • 2(0) 123 (0) would be 21230 (first zero in brackets removed)
  • 20(0)123023(0) would be 201230230 (first zero in brackets removed)
  • 00(0)1 would be 1(leading zeros removed)
  • 001(1)(0) would be 110 (leading zeros removed)
  • 0(0)02(0) would be 20 (leading zeros removed)
  • 123(1)3 would be 12313 (characters removed)
+5
source share
4 answers

lookbehind (0) , , .

( )


,

, (0), :

^[0\D]+|(?<=^[^(]*)\(0\)|\D

, lookbehind (.. , *), -.NET .

^[0\D]+      # zeroes and non-digits at start of string
|            # or
(?<=^[^(]*)  # preceded by start of string and only non-"(" chars
\(0\)        # "(0)"
|            # or
\D           # non-digit, equivalent to "[^\d]"

( regexhero.net)


. , , , , . , , , . , :

  • .
  • .
  • .

, ( ), .

+5

, .

(^[^\d])|([^\d](0[^\d])?)+

( , )

EDIT:

, . , , ( ):

string[] entries = new string[7] {
    "800 (0) 123 - 1",
    "800 (1) 123",
    "(0)321 123",
    "1 (0) 1",
    "1 (12) (0) 1",
    "1 (0) (0) 1",
    "(9)156 (1) (0)"
};
foreach (string entry in entries)
{
    var output = Regex.Replace(entry , @"\(0\)\s*\(0\)", "0");
    output = Regex.Replace(output, @"\s\(0\)", "");
    output = Regex.Replace(output, @"[^\d]", "");
    System.Console.WriteLine("---");
    System.Console.WriteLine(entry);
    System.Console.WriteLine(output);
}
+1

, . , , (0), , , :

var noMidStrParenZero = Regex.Replace(text, "^([^(]+)\(0\)", "$1");
var finalStr = Regex.Replace(noMidStrParenZero, "[^0-9]", "");

, .

EDIT: .

+1
(?:     # start grouping
    ^   # start of string
    |   # OR
    ^\( # start of string followed by paren
    |   # OR
    \d  # a digit
)       # end grouping
(0+)    # capture any number of zeros
|       # OR
([1-9]) # capture any non-zero digit

This works for all of your sample lines , but the whole expression matches (, followed by zero. You can use Regex.Matchesto get a collection of matches using global matching, and then append all the matching groups to the string to get only numbers (or just delete any non-numbers).

0
source

All Articles