Related
I have string in text that have uses | as a delimiter.
Example:
|2P|1|U|F8|
I want the result to be 2P|1|U|F8. How can I do that?
The regex is very easy, but why not just use Trim():
var str = "|2P|1|U|F8|";
str = str.Trim(new[] {'|'});
or just without new[] {...}:
str = str.Trim('|');
Output:
In case there are leading/trailing whitespaces, you can use chained Trims:
var str = "\r\n |2P|1|U|F8| \r\n";
str = str.Trim().Trim('|');
Output will be the same.
You can use String.Substring:
string str = "|2P|1|U|F8|";
string newStr = str.Substring(1, str.Length - 2);
Just remove the starting and the ending delimiter.
#"^\||\|$"
Use the below regex and then replace the match with an empty string.
Regex rgx = new Regex(#"^\||\|$");
string result = rgx.Replace(input, "");
Use mulitline modifier m when you're dealing with multiple lines.
Regex rgx = new Regex(#"(?m)^\||\|$");
Since | is a special char in regex, you need to escape this in-order to match a literal | symbol.
string input = "|2P|1|U|F8|";
foreach (string item in input.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
Console.WriteLine(item);
}
Result is:
2P
1
U
F8
^\||\|$
You can try this.Replace by empty string.Use verbatim mode.See demo.
https://regex101.com/r/oF9hR9/14
For completionists-sake, you can also use Mid
Strings.Mid("|2P|1|U|F8|", 2, s.Length - 2)
This will cut out the part from the second character to the previous to last one and produce the correct output.
I'm assuming that at some point you will want to parse the string to extract its '|' separated components, so here goes another alternative that goes in that direction:
string.Join("|", theString.Split(new[] {'|'}, StringSplitOptions.RemoveEmptyEntries))
I have a string 4(4X),4(4N),3(3X) from this string I want to make string 4,4,3. If I am getting the string 4(4N),3(3A),2(2X) then I want to make my string 4,3,2.
Please someone tell me how can I solve my problem.
This Linq query selects substring from each part of input string, starting from beginning till first open brace:
string input = "4(4N),3(3A),2(2X)";
string result = String.Join(",", input.Split(',')
.Select(s => s.Substring(0, s.IndexOf('('))));
// 4,3,2
This may help:
string inputString = "4(4X),4(4N),3(3X)";
string[] temp = inputString.Split(',');
List<string> result = new List<string>();
foreach (string item in temp)
{
result.Add(item.Split('(')[0]);
}
var whatYouNeed = string.Join(",", result);
You can use regular expressions
String input = #"4(4X),4(4N),3(3X)";
String pattern = #"(\d)\(\1.\)";
// ( ) - first group.
// \d - one number
// \( and \) - braces.
// \1 - means the repeat of first group.
String result = Regex.Replace(input, pattern, "$1");
// $1 means, that founded patterns will be replcaed by first group
//result = 4,4,3
For Example, I have a string like :
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
I want to delete the charaters ,phani from str.
Now, I am using str = str.Replace(",phani", string.Empty);
then my output is : str="santhosh,ravi123,praveen,sathish,prakash";
But I want a output like : str="santhosh,ravi,phani123,praveen,sathish,prakash";
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
var words = str.Split(',');
str = String.Join(",", words.Where(word => word != "phani"));
the better choice is to use a Split and Join method.
Easy in Linq :
String str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
String token = "phani";
String result = String.Join(",", str.Split(',').Where(s => s != token));
(edit : I take time for testing and i'm not first ^^)
String.join(",", str.split(',').ToList().remove("phani"));
Removes any given name from the list.
How about
str = str.Replace(",phani,", ",");
This, however, does not work if "phani" is the last item in the string. To get around this, you could do this:
string source = "...";
source += ","; // Explicitly add a comma to the end
source = source.Replace(",phani,", ",").TrimEnd(',');
This adds a comma, replaces "phani" and removes the trailing comma.
A third solution would be this:
str = String.Join(",", str.Split(',').ToList().Remove("phani").ToArray());
Try to use with comma instead of;
string str = "santhosh,ravi,phani,phani123,praveen,sathish,prakash";
str = str.Replace(",phani,", ",");
Console.WriteLine(str);
Output will be;
santhosh,ravi,phani123,praveen,sathish,prakash
Here is a DEMO.
As Davin mentioned in comment, this won't work if phani is last item in the string. Silvermind's answer looks like the right answer.
string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
string pattern = #"\b,phani,\b";
string replace = ",";
Console.WriteLine(Regex.Replace(str, pattern, replace));
Output:
santhosh,ravi,phani123,praveen,sathish,prakash
You may use the regular expression, but you have to take care of cases when your string starts or ends with the substring:
var pattern = #",?\bphani\b,?";
var regex = new Regex(pattern);
var result = regex.Replace(input, ",").Trim(',');
Shorter notation could look like this:
var result = Regex.Replace(input, #",?\bphani\b,?", ",").Trim(',');
Explanation of the regular expression: ,?\bphani\b,? matches the word phani, 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.
I have a string of type "24;#usernamehere,#AWRFR\user,#,#,#usernamehere"
I want to split this string on the first appearance on # and , i.e i want a string to be fetched which is inbetween these two characters.
So for the above string i want the OUTPUT as:
usernamehere
How can i split a string in between two characters using Regex function?
A simple Regex Pattern might do the job:
var pattern = new System.Text.RegularExpressions.Regex("#(?<name>.+?),");
test:
string s = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
pattern.Match(s).Groups["name"].Value; //usernamehere
Using Linq:
using System.Linq;
var input = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
You can split it with a single line:
var x = input.Split('#').Where(e => e.Contains(',')).Select(e => e.Split(',').First());
which is the same as:
var x = from e in input.Split('#')
where e.Contains(',')
select e.Split(',').First();
in both cases the result would be:
x = {"usernamehere", "AWRFR\user", "", ""}
Which is exactly an array with all substrings enclosed by # and ,.
Then if you want the first element just add .First() or do:
x.First();
You need to find the first index of '#' & ','. Then use substring method to get your required trimmed string. Read this for more details on substring method
string s = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string finalString = s.Substring(s.IndexOf('#') + 1, s.IndexOf(',') - s.IndexOf('#') - 1);
Not exactly the way you asked for it, but should do what you want...
string input = #"24;#usernamehere,#AWRFR\user,#,#,#usernamehere";
string username = input.Substring(input.LastIndexOf("#") + 1);
If you wanted you could get the position of the first # and the ,
int hashPosition = input.IndexOf("#") + 1;
int commaPosition = input.IndexOf(",");
string username = input.Substring(hashPosition, commaPosition - hashPosition));
I need to remove all chars that cant be part of urls, like spaces ,<,> and etc.
I am getting the data from database.
For Example if the the retrieved data is: Product #number 123!
the new string should be: Product-number-123
Should I use regex? is there a regex pattern for that?
Thanks
Here is a an example on how to generate an url-friendly string from a "normal" string:
public static string GenerateSlug(string phrase)
{
string str = phrase.ToLower();
str = Regex.Replace(str, #"[^a-z0-9\s-]", ""); // invalid chars
str = Regex.Replace(str, #"\s+", " ").Trim(); // convert multiple spaces into one space
str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); // cut and trim it
str = Regex.Replace(str, #"\s", "-"); // hyphens
return str;
}
You may want to remove the trim-part if you are sure that you always want the full string.
Source
An easy regex to do this is:
string cleaned = Regex.Replace(url, #"[^a-zA-Z0-9]+","-");
To just perform the replacement of special characters like "<" you can use Server.UrlEncode(string s). And you can do the opposite with Server.UrlDecode(string s).