Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format string with regex in c#

Tags:

c#

regex

I would like to format a string that looks like this

BPT4SH9R0XJ6

Into something that looks like this

BPT4-SH9R-0XJ6

The string will always be a mix of 12 letters and numbers

Any advice will be highly appreciated, thanks

like image 915
Eric Herlitz Avatar asked Apr 23 '12 18:04

Eric Herlitz


People also ask

Can you use regex in C?

A regular expression is a sequence of characters that is used to search pattern. It is mainly used for pattern matching with strings, or string matching, etc. They are a generalized way to match patterns with sequences of characters. It is used in every programming language like C++, Java, and Python.

Does Scanf use regex?

scanf does not support regexp in any standard C.

How do you denote special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

What is Reg_extended?

REG_EXTENDED. Treat the pattern as an extended regular expression, rather than as a basic regular expression. REG_ICASE. Ignore case when matching letters.


2 Answers

Try Regex.Replace(input, @"(\w{4})(\w{4})(\w{4})", @"$1-$2-$3");

Regex is often derided, but is a pretty neat way of doing what you need. Can be extended to more complex requirements that are difficult to meet using string methods.

like image 124
Olly Avatar answered Oct 24 '22 04:10

Olly


You can use "(.{4})(.{4})(.{4})" as your expression and "$1-$2-$3" as your replacement. This is, however, hardly a good use for regexp: you can do it much easier with Substring.

var res = s.Substring(0,4)+"-"+s.Substring(4,4)+"-"+s.Substring(8);
like image 32
Sergey Kalinichenko Avatar answered Oct 24 '22 04:10

Sergey Kalinichenko