C# String Split Between Dividers - c#

Maybe I misunderstood the title, sorry.
I have a string;
This is a test string. It was opened on %Date% for the customer named
%Customer%.
Here I want to be able to get a string containing "Date" and "Customer" with a method. How do I get the parts between the special characters "%" as strings?
Divider character and string can change dynamically. Thanks in advance.

You could extract it with System.Text.RegularExpressions.RexEx()
%[^%]*%" - starts with %, ends with % but doesn't contain it [^%]*
string str = "This is a test string. It was opened on %Date% for the customer named %Customer%.";
string[] res = Regex.Matches(str, "%[^%]*%").Cast<Match>().Select(x => x.Value.Trim('%')).ToArray();

Related

Match Characters after last dot in string

I have a string and I want to get the words after the last dot in the string.
Example:
input string = "XimEngine.DynamicGui.PickKind.DropDown";
Result:
DropDown
There's no need in Regex, let's find out the last . and get Substring:
string result = input.Substring(input.LastIndexOf('.') + 1);
If input doesn't have . the entire input will be returned
Not a RegEx answer, but you could do:
var result = input.Split('.').Last();
In Regex you can tell the parser to work from the end of the string/buffer by specifying the option RightToLeft.
By using that we can just specify a forward pattern to find a period (\.) and then capture (using ( )) our text we are interested into group 1 ((\w+)).
var str = "XimEngine.DynamicGui.PickKind.DropDown";
Console.WriteLine(Regex.Match(str,
#"\.(\w+)",
RegexOptions.RightToLeft).Groups[1].Value);
Outputs to console:
DropDown
By working from the other end of the string means we don't have to deal with anything at the beginning of the string to where we need to extract text.

C# Extract part of the string that starts with specific letters

I have a string which I extract from an HTML document like this:
var elas = htmlDoc.DocumentNode.SelectSingleNode("//a[#class='a-size-small a-link-normal a-text-normal']");
if (elas != null)
{
//
_extractedString = elas.Attributes["href"].Value;
}
The HREF attribute contains this part of the string:
gp/offer-listing/B002755TC0/
And I'm trying to extract the B002755TC0 value, but the problem here is that the string will vary by its length and I cannot simply use Substring method that C# offers to extract that value...
Instead I was thinking if there's a clever way to do this, to perhaps a match beginning of the string with what I search?
For example I know for a fact that each href has this structure like I've shown, So I would simply match these keywords:
offer-listing/
So I would find this keyword and start extracting the part of the string B002755TC0 until the next " / " sign ?
Can someone help me out with this ?
This is a perfect job for a regular expression :
string text = "gp/offer-listing/B002755TC0/";
Regex pattern = new Regex(#"offer-listing/(\w+)/");
Match match = pattern.Match(text);
string whatYouAreLookingFor = match.Groups[1].Value;
Explanation : we just match the exact pattern you need.
'offer-listing/'
followed by any combination of (at least one) 'word characters' (letters, digits, hyphen, etc...),
followed by a slash.
The parenthesis () mean 'capture this group' (so we can extract it later with match.Groups[1]).
EDIT: if you want to extract also from this : /dp/B01KRHBT9Q/
Then you could use this pattern :
Regex pattern = new Regex(#"/(\w+)/$");
which will match both this string and the previous. The $ stands for the end of the string, so this literally means :
capture the characters in between the last two slashes of the string
Though there is already an accepted answer, I thought of sharing another solution, without using Regex. Just find the position of your pattern in the input + it's lenght, so the wanted text will be the next character. to find the end, search for the first "/" after the begining of the wanted text:
string input = "gp/offer-listing/B002755TC0/";
string pat = "offer-listing/";
int begining = input.IndexOf(pat)+pat.Length;
int end = input.IndexOf("/",begining);
string result = input.Substring(begining,end-begining);
If your desired output is always the last piece, you could also use split and get the last non-empty piece:
string result2 = input.Split(new string[]{"/"},StringSplitOptions.RemoveEmptyEntries)
.ToList().Last();

C# Coding using strings in order to find a full name

I am using Visual studio to create a C# windows form that helps me find the suffix,first and last name of the user. I am using string.split to find the first space and split from there but it only gives me from the first space onward. if the user input " Mr. Donald duck " I can not manage to make it work in the situation.
"Mr. -5 spaces- Donald -5spaces- Duck"
the code doesn't read past the first space.
any suggestions?
Trimming is only going to take care of leading and trailing white-space characters. Here's what you need in order to get just the 3 useful parts of the text when you have all those extra spaces between words:
string name = "Mr. Donald Duck";
string[] split = name.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
The string array will contain 3 items: Mr., Donald, and Duck. The StringSplitOptions.RemoveEmptyEntries will take care of repeating white-space when you split the original string.
Without it, you get something like this: Mr., , , , , Donald, , , , , Duck
You should always use String.Trim() function. (To remove leading and trailing white-space from string) when you deal with user input as a string.
string s = " Mr. Donald duck ";
// Split string on spaces.
// ... This will separate all the words.
string[] words = s.Trim().Split(' ');
//.....check size of array.
if(words.Length ==3)
{
string suffix=words[0];
string firstname=words[1];
string lastname=words[2];
}
I am not getting -5 in your question but hope this will help.
Split with remove empty string option, then you will get non empty word array as result. From that you can get name parts.
Demo
The Syntax for String.Split would be like this:
// 0 1 2
// ooo|oooooo|oooo
string str = "Mr. Donald Duck";
string suffix = str.Split(' ')[0];
string fname = str.Split(' ')[1];
string lname = str.Split(' ')[0];
Just for explanation
According to MSDN You can easily remove white spaces from both ends of a string by using the String.Trim method. You can read it here. For more good understanding you can visit here
string input = Console.ReadLine();
// This will remove white spaces from both ends and split on the basis of spaces in string.
string[] tokens = input.Trim().Split(' ');
string title = tokens[0];
string firstname = tokens[1];
string secondname = tokens[2];

Extracting only the substring containing letters from a string containing digits strings and symbols

I have a string that is like the following:
string str = hello_16_0_2016;
What I want is to extract hello from the string. As in my program the string part can occur anywhere as it is autogenerated, so I cannot fix the position of my string.
For example: I can take the first five string from above and store it in a new variable.
But as occurring of letters is random and I want to extract only letters from the string above, so can someone guide me to the correct procedure to do this?
Could you just use a simple regular expression to pull out only alphabetic characters, assuming you only need a-z?
using System.Text.RegularExpressions;
var str = "hello_16_0_2016";
var onlyLetters = Regex.Replace(str, #"[^a-zA-Z]", "");
// onlyLetters = "hello"
I'd use something like this (uses Linq):
var str = "hello_16_0_2016";
var result = string.Concat(str.Where(char.IsLetter));
Check it out
Or, if performance is a concern (because you have to do this on a tight loop, or have to convert hundreds of thousands of strings), it'd probably be faster to do:
var result = new string(str.Where(char.IsLetter).ToArray());
Check it too
But as occurring of letters is random and I want to extract only
letters from the string above, so can someone guide me to the correct
procedure to do this?
The following will extract the first text, without numbers anywhere in the string:
Console.WriteLine( Regex.Match("hello_16_0_2016", #"[A-Za-z]+").Value ); // "hello"

C# Split string emails

In my table of database MySQL I've stored this string example:
name.surname#thedomain.com
I need spli this string in C# for this output
NAME SURNAME
And tried this solution:
string[] emails = strEMail_user.ToString().Split('.');
string newUserName = emails[0].ToUpper().ToString() + " "
+ emails[1].ToUpper().ToString();
But I've in output this wrong string :
NAME SURNAME#THEDOMAIN.
If this is your pattern name.surname#thedomain.com then you can just use Split with two delimiters, and get first and second parts:
var parts = "name.surname#thedomain.com".Split('.', '#');
string name = parts[0];
string surname = parts[1];
You could do this using a combination of string.Split calls, but it would be much neater to use the Regex class to do this.
Your regex should look something like this:
([a-zA-Z]*)\.([a-zA-Z]*)#thedomain\.com
You can then use the Regex.Match method to obtain the values from the matching groups.
Use strEMail_user.ToString().Split('#')[0] as first part of your email, where name and surname are stored. Then you can split that by . to get name and surname just like you did, if that's the pattern of your emails.
You are splitting the string name.surname#thedomain.com on the . character. That will give you the following pieces:
name
surname#thedomain
com
Remember, there is a .com at the end of your string. What you want to do is split just the beginning of the email address. Try splitting the entire email address first on the # symbol to return the following pieces:
name.surname
thedomain.com
Now you can split the first piece on the . character to get your name and surname.
Note that this is completely assumes that all of your email addresses are of this form, and ignores cultural differences in first name/last name placement.

Categories