How can I append a known string before each coma on a comma separated string.
Is there a regex for that or something that doesn't use a loop
EX
given string :
email, email2, email3 (etc...)
to
string suffix = "#iou.com"
string desiredResult = "email#iou.com, email2#iou.com, email3#iou.com
Thank you!!
You can use [^,\s]+ regexp, and replace with "$0"+suffix:
var res = Regex.Replace(original, #"[^,\s]+", "$0"+suffix);
"$0" refers to the content captured by the regular expression.
Demo.
Or using LINQ:
Console.WriteLine(string.Join(",",input.Split(',').Select(s => string.Concat(s, suffix))));
You could use a zero-length capture group. Here's how that might look:
\w+(?<ReplaceMe>),?
The \w matches alphanumeric characters, and the named capture group called "ReplaceMe" matches the zero-length space between the end of the word and the beginning of the comma (or any other non-alphanumeric item, including the end of the string).
Then you'd just replace ReplaceMe with the appended value, like this:
Regex.Replace(original, #"\w+(?<ReplaceMe>),?", "#email.com");
Here's an example ofthat regex in action.
Here you are:
string input = "email, email2, email3";
string suffix = "#iou.com";
//string desiredResult = "email#iou.com, email2#iou.com, email3#iou.com";
Console.WriteLine(Regex.Replace((input + ",")
.Replace(",", suffix + ","), #",$", ""));
Hope this helps.
Related
I have string string A = "... :-ggw..-:p";
using regex: string B = Regex.Replace(A, #"^\.+|:|-|", "").Trim();
My Output isggw..p.
What I want is ggw..-:p.
Thanks
You may use a character class with your symbols and whitespace shorthand character class:
string B = Regex.Replace(A, #"^[.:\s-]+", "");
See the regex demo
Details
^ - start of string
[.:\s-]+ - one or more characters defined in the character class.
Note that there is no need escaping . inside [...]. The - does not have to be escaped since it is at the end of the character class.
A regex isn't necessary if you only want to trim specific characters from the start of a string. System.String.TrimStart() will do the job:
var source = "... :-ggw..-:p";
var charsToTrim = " .:-".ToCharArray();
var result = source.TrimStart(charsToTrim);
Console.WriteLine(result);
// Result is 'ggw..-:p'
Regex rgx2 = new Regex("[^[0-9] . \n\r\t]");
string dash = Regex.Replace(Des_AccNo.ToString(), #" ^-");
I need to clean this string 100-0#/2^2341?! as 100022341
I don't know what is your code, but you can do that by:
val = val.Replace("-", string.Empty)
If you want to remove all non-numeric characters:
string result = Regex.Replace(inputString, #"[^0-9]", "");
Basically what that says is "if the character isn't a digit, then replace it with the empty string." The ^ as the first character in the character group negates it. That is, [0-9] matches any digit. [^0-9] matches everything except a digit. See Character Classes in the MSDN documentation.
The expression #"[^\d]" also would work
I would basically create a static class that automatically pops up against any string.
If the same is GUID, you can simply do
Guid.NewGuid().ToString("N") returns only characters
Input: 12345678-1234-1234-1234-123456789abc
Output: 12345678123412341234123456789abc
public static string ToNonDashed(this string input)
{
return input?.Replace("-", string.Empty);
}
You can try this:
Des_AccNo = Des_AccNo.Replace("-", string.Empty);
string dash = Des_AccNo.ToString().Replace("-", string.Empty);
I have extract the 3 usable field from a string. There is no common delimiter, there can be both blank spaces and tabs.
First, what I am doing is replacing all double blanks and tabs by '**'
Given String :
cont = Gallipelle 04/04/2012 16.03.03 5678
I am using:
cont.Replace(" ", "**").Replace(" ", "**").Replace(" ", "**").Replace("**", "").Trim()
The answer becomes:
****** Gallipelle******04/04/2012 16.03.03************************ 5678*****
Is the approach correct? How do I extract the stuffs from here? I just need all the extracts in string datatype.
Just use String.Split:
var fields = cont.Split(new[] { " ", "\t" },
StringSplitOptions.RemoveEmptyEntries);
Adding StringSplitOptions.RemoveEmptyEntries makes sure that if there are multiple consecutive tabs and/or spaces they will "count as one" when extracting the results.
An alternate option would be to use a regular expression.
You can use regex groups to find out three values name, date, number.
A group is defined as (?<group_name><regex_expr>)
So you could write
Regex regex = new Regex("(?<name>(\\S*))(\\s*)(?<date>((\\S*)\\s(\\S*)))(\\s*)(?<number>(\\d*))");
Match match = regex.Match(yourString);
if (match.Success)
{
string name = match.Groups["name"].Value;
string date = match.Groups["date"].Value;
string number = match.Groups["number"].Value;
}
\s* matches sequence of whitespaces which includes tabs.
\S* matches sequence of non-whitespace characters.
\d* matches sequence of digits.
(new Regex("\\s+")).Split(yourstring)
http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx
var myText="cont = Gallipelle 04/04/2012 16.03.03 5678";
var splitString=myText.split(" ");
// splitString[1] == Gallipelle
// splitString[2] == 04/04/2012
// splitString[3] == 16.03.03
// splitString[4] == 5678
No. No need to replace it with any other delimiter. You can use String's split function and give 'space' as delimiter character. e.g. in VB.Net:
Dim value As String() = cont.split(CChar(" "))
this will give you a string array whose values you can access: value(0), value(1) and value(2)
How can I trim a string by a whole string instead of a list of single characters?
I want to remove all and whitespaces at beginning and end of an HTML string. But method String.Trim() does only have overloads for set of characters and not for set of strings.
You could use HttpUtility.HtmlDecode(String) and use the resultant as an input for String.Trim()
HttpUtility.HtmlDecode on MSDN
HttpServerUtility.HtmlDecode on MSDN (a wrapper you can access through the Page.Server property)
string stringWithNonBreakingSpaces;
string trimmedString = String.Trim(HttpUtility.HtmlDecode(stringWithNonBreakingSpaces));
Note: This solution would decode all the HTML strings in the input.
The Trim method removes from the current string all leading and trailing white-space characters by default.
Edit: Solution for your problem AFTER your edit:
string input = #" <a href='#'>link</a> ";
Regex regex = new Regex(#"^( |\s)*|( |\s)*$");
string result = regex.Replace(input, String.Empty);
This will remove all trailing and leading spaces and . You can add any string or character group to the expression. If you were to trim all tabs too the regex would simply become:
Regex regex = new Regex(#"^( |\s|\t)*|( |\s|\t)*$");
Not sure if this is what you're looking for?
string str = "hello ";
str.Replace(" ", "");
str.Trim();
Use RegEx, as David Heffernan said. It is rather easy to select all spaces at the start of string: ^(\ | )*
string myNumber = "3.44";
Regex regex1 = new Regex(".");
string[] substrings = regex1.Split(myNumber);
foreach (var substring in substrings)
{
Console.WriteLine("The string is : {0} and the length is {1}",substring, substring.Length);
}
Console.ReadLine();
I tried to split the string by ".", but it the splits return 4 empty string. Why?
. means "any character" in regular expressions. So don't split using a regex - split using String.Split:
string[] substrings = myNumber.Split('.');
If you really want to use a regex, you could use:
Regex regex1 = new Regex(#"\.");
The # makes it a verbatim string literal, to stop you from having to escape the backslash. The backslash within the string itself is an escape for the dot within the regex parser.
the easiest solution would be: string[] val = myNumber.Split('.');
. is a reserved character in regex. if you literally want to match a period, try:
Regex regex1 = new Regex(#"\.");
However, you're better off simply using myNumber.Split(".");
The dot matches a single character, without caring what that character
is. The only exception are newline characters.
Source: http://www.regular-expressions.info/dot.html
Therefore your implying in your code to split the string at each character.
Use this instead.
string substr = num.Split('.');
Keep it simple, use String.Split() method;
string[] substrings = myNumber.Split('.');
It has an other overload which allows specifying split options:
public string[] Split(
char[] separator,
StringSplitOptions options
)
You don't need regex you do that by using Split method of string object
string myNumber = "3.44";
String[] substrings = myNumber.Split(".");
foreach (var substring in substrings)
{
Console.WriteLine("The string is : {0} and the length is {1}",substring, substring.Length);
}
Console.ReadLine();
The period "." is being interpreted as any single character instead of a literal period.
Instead of using regular expressions you could just do:
string[] substrings = myNumber.Split(".");
In Regex patterns, the period character matches any single character. If you want the Regex to match the actual period character, you must escape it in the pattern, like so:
#"\."
Now, this case is somewhat simple for Regex matching; you could instead use String.Split() which will split based on the occurrence of one or more static strings or characters:
string[] substrings = myNumber.Split('.');
try
Regex regex1 = new Regex(#"\.");
EDIT: Er... I guess under a minute after Jon Skeet is not too bad, anyway...
You'll want to place an escape character before the "." - like this "\\."
"." in a regex matches any character, so if you pass 4 characters to a regex with only ".", it will return four empty strings. Check out this page for common operators.
Try
Regex regex1 = new Regex("[.]");