This question already has answers here:
return only Digits 0-9 from a String
(8 answers)
Closed 3 years ago.
Is there any better way to get take a string such as "(123) 455-2344" and get "1234552344" from it than doing this:
var matches = Regex.Matches(input, #"[0-9]+", RegexOptions.Compiled);
return String.Join(string.Empty, matches.Cast<Match>()
.Select(x => x.Value).ToArray());
Perhaps a regex pattern that can do it in a single match? I couldn't seem to create one to achieve that though.
Do you need to use a Regex?
return new String(input.Where(Char.IsDigit).ToArray());
Have you got something against Replace?
return Regex.Replace(input, #"[^0-9]+", "");
You'll want to replace /\D/ (non-digit) with '' (empty string)
Regex r = new Regex(#"\D");
string s = Regex.Replace("(123) 455-2344", r, "");
Or more succinctly:
string s = Regex.Replace("(123) 455-2344", #"\D",""); //return only numbers from string
Just remove all non-digits:
var result = Regex.Replace(input, #"\D", "");
In perl (you can adapt this to C#) simply do
$str =~ s/[^0-9]//g;
I am assuming that your string is in $str. Basic idea is to replace all non digits with '' (i.e. empty string)
Related
This question already has answers here:
How to replace the text between two characters in c#
(7 answers)
Closed 5 years ago.
I was wondering how do I use regex to replace string between two characters.
var oldString = "http://localhost:61310/StringtoConvert?Id=1"
Expected result = "http://localhost:61310/ConvertedString?Id=1"
No need for regex or string operations, use UriBuilder class.
var oldString = "http://localhost:61310/StringtoConvert?Id=1";
var newuri = new UriBuilder(new Uri(oldString));
newuri.Path = "ConvertedString";
var result = newuri.ToString();
You can use Regex.Replace(string, string, string). So, if you want to replace a substring between a / and a ?, you can use
string result = Regex.Replace(oldString, "(?<=\/)[^\?]*(?=\?)", "ConvertedString");
?<= is a lookbehind, \/ escapes the slash character, [^\?]* matches any characters not a ? any number of times, ?= is a lookahead, and \? escapes the question mark character.
Instead of Regex, you can use the System.Uri class then concatenate or interpolate your new value:
private static string ReplacePath(string url, string newPath)
{
Uri uri = new Uri(url);
return $"{uri.GetLeftPart(UriPartial.Authority)}/{newPath}{uri.Query}";
}
Calling this method with your url, and the new path (ie "ConvertedString") will result in the output: "http://localhost:61310/ConvertedString?Id=1"
Fiddle here.
EDIT
#Eser's answer is way better than mine. Did not know that class existed. Mark their answer as the right one not mine.
This question already has answers here:
Using regex to extract multiple numbers from strings
(4 answers)
Closed 5 years ago.
I have an input string like below:
"/myWS/api/Application/IsCarAvailable/123456/2017"
It is the end of a Web API call that I am making. I need to easily extract the 123456 from the URL.
I was hoping something like the below would work
string[] numbers = Regex.Split(input, #"\D+");
However, when I set a breakpoint on numbers and run the code it is showing an array of 3 elements?
Element at [0] is ""
Element at [1] is 123456
Element at [2] is 2017
Does anyone see why it would be getting the empty string as the first element?
I suggest matching, not splitting:
string source = #"/myWS/api/Application/IsCarAvailable/123456/2017";
string[] numbers = Regex
.Matches(source, "[0-9]+")
.OfType<Match>()
.Select(match => match.Value)
.ToArray();
Please, notice that \d+ in .Net means any unicode digits (e.g. Persian ones: ۰۱۲۳۴۵۶۷۸۹): that's why I put [0-9]+ pattern (RegexOptions.ECMAScript is an alternative if \d+ pattern is preferrable).
If your string is always in the same format, this would work:
string numbers = input.Split('/')[input.Split('/').Length - 2];
I think this is because the split method "splits" the string at the matching expression. So the empty string is the part before the first match.
Any reason why you would not use Regex.Matches(input,"\\d+") instead?
string numtest = "http://www.google.com/test/123456/7890";
var matchResult = Regex.Matches(numtest, "\\d+");
for (int i = 0; i < matchResult.Count; i++)
Console.WriteLine($"Element {i} is {matchResult[i].Value}");
Hope that helps. Regards!
This question already has answers here:
Regex to replace invalid characters
(3 answers)
Closed 6 years ago.
I have a list of allowed characters in my application.
1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .,'()?!#$%^*;:+=-_
What i want's if my string contain any characters other then above it will be replace with string.empty
How can i do it
If you have a list of allowed characters, I suggest testing against this list; something like that (Linq):
// HashSet is efficient to find items O(1)
private static HashSet<char> s_Allowed = new HashSet<char>(
#"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.,'()?!#$%^*;:+=");
...
string source = "123~~~456";
// "123456"
string result = string.Concat(source
.Where(c => s_Allowed.Contains(c)));
You can use a regex replacement. Try this:
public static string formatToken(string token)
{
//To prevent null exception
if (string.IsNullOrWhiteSpace(token)) return token;
Regex rgx = new Regex("[^a-zA-Z0-9 .,'()?!#$%*;:+=-_]"); //Maybe some characters need to be scaped.
return rgx.Replace(token, "");
}
This question already has answers here:
How to remove the exact occurence of characters from a string?
(7 answers)
Closed 6 years ago.
i have a string like string st ="12,34,56,345,12,45" and i want remove number 34 from this string i did like string newst = st.replace(",34",""); but it is removing 34 from 345 , how to prevent this
EDIT
34 can be anywhere,here i am generating dynamically
It's very simple:
var st ="12,34,56,345,12,45";
var newst = st.replace(",34,", ",");
If it can be anywhere, you may use the regular expression:
var input = "34,234,35,36,34,37,345,34";
var pattern = #",?\b34\b,?";
var regex = new Regex(pattern);
var result = regex.Replace(input, ",").Trim(',');
Shorter notation could look like this:
var result = Regex.Replace(input, #",?\b34\b,?", ",").Trim(',');
Explanation of the regular expression: ,?\b34\b,? matches the word 34, but only if preceded and followed by word-delimiter characters (because of the word boundary metacharacter \b), and it can be (but doesn't have to be) preceded and followed by the comma thanks to ,? which means none or more comma(s).
At the end we need to remove possible commas from the beginning and end of the string, that's why there's Trim(',') on the result.
But I would say #crashmstr's solution is better than trying to tune the regular expression for this particular use case.
This will work:
var oldString = "34,12,34,56,345,12,45,34";
var newString = String.Join(",", oldString.Split(',').Where(x => x != "34"));
We split on ',', use LINQ to exclude "34", then join the string back together by ','.
Try this
string newst = st.replace(",34,",",");
Granted this only works if the number you want to replace is between two commas. If you want something more advanced, use Regex.Replace()
Here's an example:
string temp = Regex.Replace("12,34,56,345,12,45", #"^34,", "");
string newst = Regex.Replace(temp, #"34$,", "");
You could also use String.TrimStart and .TrimEnd to clean up the borders.
Also, I like crashmstr's example.
split and work in list:
string[] arr = st.Split(',');
List<string> list = arr.ToList();
list.Remove("34");
or regex:
var replaced = Regex.Replace(st, #"\b34\b[,]","");
I want to match only numbers in the following string
String : "40’000"
Match : "40000"
basically tring to ignore apostrophe.
I am using C#, in case it matters.
Cant use any C# methods, need to only use Regex.
Replace like this it replace all char excpet numbers
string input = "40’000";
string result = Regex.Replace(input, #"[^\d]", "");
Since you said; I just want to pick up numbers only, how about without regex?
var s = "40’000";
var result = new string(s.Where(char.IsDigit).ToArray());
Console.WriteLine(result); // 40000
I suggest use regex to find the special characters not the digits, and then replace by ''.
So a simple (?=\S)\D should be enough, the (?=\S) is to ignore the whitespace at the end of number.
DEMO
Replace like this it replace all char excpet numbers and points
string input = "40’000";
string result = Regex.Replace(input, #"[^\d^.]", "");
Don't complicate your life, use Regex.Replace
string s = "40'000";
string replaced = Regex.Replace(s, #"\D", "");