Formatting a Phone number [duplicate] - c#

This question already has answers here:
Replace non-numeric with empty string
(9 answers)
Closed 8 years ago.
How can I format a phone number from (###)###-#### to ##########? Is there best way to do that? I can use String.Substring to get each block of numbers and then concatenate them. But, Is there any other sophisticated way of doing it?

How about a simple Regex replace?
string formatted = Regex.Replace(phoneNumberString, "[^0-9]", "");
This is essentially just a white list for numbers only. See this fiddle: http://dotnetfiddle.net/ssdWSd
Input: (123) 456-7890
Output: 1234567890

I'd do it using LINQ:
var result = new String(phoneString.Where(x => Char.IsDigit(x)).ToArray());
While regex also works, this doesn't require any special set up.

A simple way would be:
myString = myString.Replace("(", "");
myString = myString.Replace(")", "");
myString = myString.Replace("-", "");
Replace each character with an empty string.

Try this:
resultString = Regex.Replace(subjectString, #"^\((\d+)\)(\d+)-(\d+)$", "$1$2$3");
REGEX EXPLANATION
^\((\d+)\)(\d+)-(\d+)$
Assert position at the beginning of the string «^»
Match the character “(” literally «\(»
Match the regex below and capture its match into backreference number 1 «(\d+)»
Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “)” literally «\)»
Match the regex below and capture its match into backreference number 2 «(\d+)»
Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “-” literally «-»
Match the regex below and capture its match into backreference number 3 «(\d+)»
Match a single character that is a “digit” (0–9 in any Unicode script) «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at the end of the string, or before the line break at the end of the string, if any (line feed) «$»
$1$2$3
Insert the text that was last matched by capturing group number 1 «$1»
Insert the text that was last matched by capturing group number 2 «$2»
Insert the text that was last matched by capturing group number 3 «$3»

Related

Regex to match trimmed string consisting of words separated by only 1 space char

I am looking for a regex to validate input in C#. The regex has to match an arbitrary number of words which are separated with only 1 space character in between. The matched string cannot start or end with whitespace characters (this is where my problem is).
Example: some sample input 123
What I've tried: /^(\S+[ ]{0,1})+$/gm this pattern almost does what is required but it also matches 1 trailing space.
Any ideas? Thanks.
I tried this one and it seems to work:
Regex regex = new Regex(#"^\S+([ ]{1}\S+)*$");
It checks if your string starts with a word followed by zero or more entities of a single white space followed by a word. So trailing white spaces are not allowed.

Regex Substring or Left Equivalent

Greetings beloved comrades.
I cannot figure out how to accomplish the following via a regex.
I need to take this format number 201101234 and transform it to 11-0123401, where digits 3 and 4 become the digits to the left of the dash, and the remaining five digits are inserted to the right of the dash, followed by a hardcoded 01.
I've tried http://gskinner.com/RegExr, but the syntax just defeats me.
This answer, Equivalent of Substring as a RegularExpression, sounds promising, but I can't get it to parse correctly.
I can create a SQL function to accomplish this, but I'd rather not hammer my server in order to reformat some strings.
Thanks in advance.
You can try this:
var input = "201101234";
var output = Regex.Replace(input, #"^\d{2}(\d{2})(\d{5})$", "${1}-${2}01");
Console.WriteLine(output); // 11-0123401
This will match:
two digits, followed by
two digits captured as group 1, followed by
five digits captured as group 2
And return a string which replaces that matched text with
group 1, followed by
a literal hyphen, followed by
group 2, followed by
a literal 01.
The start and end anchors ( ^ / $ ) ensure that if the input string does not exactly match this pattern, it will simply return the original string.
If you can use custom C# scripts, you may want to use Substring instead:
string newStr = string.Format("{0}-{1}01", old.Substring(2,2), old.Substring(4));
I don't think you really need a regex here. Substring would be better. But still if you want regex only, you can use this:
string newString = Regex.Replace(input, #"^\d{2}(\d{2})(\d+)$", "$1-${2}01");
Explanation:
^\d{2} // Match first 2 digits. Will be ignored
(\d{2}) // Match next 2 digits. Capture it in group 1
(\d+)$ // Match rest of the digits. Capture it in group 2
Now, the required digits, are in group 1 and 2, which you use in the replacement string.
Do you even SQL? Pull some levers and stuff.

Make Regex stop looking at \n

I have the following string:
"\t Product: ces DEVICE TYPE \nSometext" //between ":" and "ces" are 9 white spaces
I need to parse the part "DEVICE TYPE". I'm trying to do this with Regex. I use this expression, which works.
((?<=\bProduct:)(\W+\w+){3}\b)
this expression returns:
" ces DEVICE TYPE"
The problem is here: Some devices have a string like this:
"\t Product: ces DEVICETYPE \nSometext"
If I use the same expression to parse the device type I get this as result:
" ces DEVICETYPE \nSometext"
How do I get my regex to stop when a \n is found?
Perhaps this?
(?<=ces)[^\\n]+
If all you want is what's after ces and before \n that is..
In .NET you can use RegexOptions.Multiline. This changes the behaviour of ^ and $.
Rather than meaning the start and end of your string, they now mean start and end of any line within your string.
Regex r = new Regex(#"(?<=\bProduct:).+$", RegexOptions.Multiline);
You could use:
(?m)((?<=\bProduct:).+)
Explanation:
(?m)((?<=\bProduct:).+)
Match the remainder of the regex with the options: ^ and $ match at line breaks (m) «(?m)»
Match the regular expression below and capture its match into backreference number 1 «((?<=\bProduct:).+)»
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\bProduct:)»
Assert position at a word boundary «\b»
Match the characters “Product:” literally «Product:»
Match any single character that is not a line break character «.+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
or
((?<=\bProduct:)[^\r\n]+)
Explanation
((?<=\bProduct:)[^\r\n]+)
Match the regular expression below and capture its match into backreference number 1 «((?<=\bProduct:)[^\r\n]+)»
Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=\bProduct:)»
Assert position at a word boundary «\b»
Match the characters “Product:” literally «Product:»
Match a single character NOT present in the list below «[^\r\n]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
A carriage return character «\r»
A line feed character «\n»

Regular Expression for string

I have a string like
e.g AHDFFH XXXX
where 'AHDFFH' can be char string of any length.
AND 'XXXX' will be repeated no. of 'X' chars of any length which needs to be replaced by auto incremented database value in a table.
I need to find repeated 'X' chars from above string using regular expression.
Can anyone please help me to figure this out..??
Try this:
\b(\p{L})\1+\b
Explanation:
<!--
\b(\p{L})\1+\b
Options: case insensitive; ^ and $ match at line breaks
Assert position at a word boundary «\b»
Match the regular expression below and capture its match into backreference number 1 «(\p{L})»
A character with the Unicode property “letter” (any kind of letter from any language) «\p{L}»
Match the same text as most recently matched by capturing group number 1 «\1+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Assert position at a word boundary «\b»
-->
is your meaning some chars + (on or some)space + some numbers?
if so u can use this regexpression:
\w+\s+(\d+)
c# codes like this:
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(#"\w+\s+(\d+)");
System.Text.RegularExpressions.Match m = regex.Match("aaaa 3333");
if(m.Success) {
MessageBox.Show(m.Groups[1].Value);
}

C# regex to replace a delimiter by another one

I'm working on pl/sql code where i want to replace ';' which is commented with '~'.
e.g.
If i have a code as:
--comment 1 with;
select id from t_id;
--comment 2 with ;
select name from t_id;
/*comment 3
with ;*/
Then i want my result text as:
--comment 1 with~
select id from t_id;
--comment 2 with ~
select name from t_id;
/*comment 3
with ~*/
Can it be done using regex in C#?
Regular expression:
((?:--|/\*)[^~]*)~(\*/)?
C# code to use it:
string code = "all that text of yours";
Regex regex = new Regex(#"((?:--|/\*)[^~]*)~(\*/)?", RegexOptions.Multiline);
result = regex.Replace(code, "$1;$2");
Not tested with C#, but the regular expression and the replacement works in RegexBuddy with your text =)
Note: I am not a very brilliant regular expression writer, so it could probably have been written better. But it works. And handles both your cases with one-liner-comments starting with -- and also the multiline ones with /* */
Edit: Read your comment to the other answer, so removed the ^ anchor, so that it takes care of comments not starting on a new line as well.
Edit 2: Figured it could be simplified a bit. Also found it works fine without the ending $ anchor as well.
Explanation:
// ((?:--|/\*)[^~]*)~(\*/)?
//
// Options: ^ and $ match at line breaks
//
// Match the regular expression below and capture its match into backreference number 1 «((?:--|/\*)[^~]*)»
// Match the regular expression below «(?:--|/\*)»
// Match either the regular expression below (attempting the next alternative only if this one fails) «--»
// Match the characters “--” literally «--»
// Or match regular expression number 2 below (the entire group fails if this one fails to match) «/\*»
// Match the character “/” literally «/»
// Match the character “*” literally «\*»
// Match any character that is NOT a “~” «[^~]*»
// Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
// Match the character “~” literally «~»
// Match the regular expression below and capture its match into backreference number 2 «(\*/)?»
// Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
// Match the character “*” literally «\*»
// Match the character “/” literally «/»
A regex is not really needed - you can iterate on lines, locate the lines starting with "--" and replace ";" with "~" on them.
String.StartsWith("--") - Determines whether the beginning of an instance of String matches a specified string.
String.Replace(";", "~") - Returns a new string in which all occurrences of a specified Unicode character or String in this instance are replaced with another specified Unicode character or String.

Categories