C# Split string emails - c#

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.

Related

C# String Split Between Dividers

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();

Split string from particular regular expression in c#

i have one string like
"8/6/08mz: Last name corrected from Paniaguato Arevalo-Paniaguaas listed on bills/MR, email Shasta, 1132644 06/24/08jh:To
Concentra/froi."
and i want to split this string when i get "8/6/08mz:" pattern so my updated string will be following
"8/6/08mz: Last name corrected from Paniaguato Arevalo-Paniaguaas listed on bills/MR, email Shasta, 1132644"
"06/24/08jh:To Concentra/froi."
how can i do it in c# please help me.
Using Regex.Split() and a Regular Expression?
I have a very bad one here:
[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{1,2}[a-z]{2}:
https://regex101.com/r/cEFbbZ/1
You can verify the string starts with what you want, then split on the space preceded by 7 digits:
if (s.StartsWith("8/6/08mz: ")) {
var ans = Regex.Split(s, #"(?<=[0-9]{7}) ");
}

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];

Split name with a regular expression

I'm trying to come up with regular expression which will split full names.
The first part is validation - I want to make sure the name matches the pattern "Name Name" or "Name MI Name", where MI can be one character optionally followed by a period. This weeds out complex names like "Jose Jacinto De La Pena" - and that's fine. The expression I came up with is ^([a-zA-Z]+\s)([a-zA-Z](\.?)\s){0,1}([a-zA-Z'-]+)$ and it seems to do the job.
But how do I modify it to split the name into two parts only? If middle initial is present, I want it to be a part of the first "name", in other words "James T. Kirk" should be split into "James T." and "Kirk". TIA.
Just add some parenthesis
^(([a-z]+\s)([a-z](\.?))\s){0,1}([a-z'-]+)$
Your match will be in group 1 now
string resultString = null;
try {
resultString = Regex.Match(subjectString, #"^(([a-z]+\s)([a-z](\.?))\s){0,1}([a-z'-]+)$", RegexOptions.IgnoreCase).Groups[1].Value;
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
Also, I made the regex case insensitive so that you can make it shorter (no a-zA-Z but a-z)
Update 1
The number groups don't work well for the case there is no initial so I wrote the regex from sratch
^(\w+\s(\w\.\s)?)(\w+)$
\w stands for any word charater and this is maybe what you need (you can replace it by a-z if that works better)
Update 2
There is a nice feature in C# where you can name your captures
^(?<First>\w+\s(?:\w\.\s)?)(?<Last>\w+)$
Now you can refer to the group by name instead of number (think it's a bit more readable)
var subjectString = "James T. Kirk";
Regex regexObj = new Regex(#"^(?<First>\w+\s(?:\w\.\s)?)(?<Last>\w+)$", RegexOptions.IgnoreCase);
var groups = regexObj.Match(subjectString).Groups;
var firstName = groups["First"].Value;
var lastName = groups["Last"].Value;
You can accomplish this by making what is currently your second capturing group a non-capturing group by adding ?: just before the opening parentheses, and then moving that entire second group into the end of the first group, so it would become the following:
^([a-zA-Z]+\s(?:[a-zA-Z](\.?)\s)?)([a-zA-Z'-]+)
Note that I also replaced the {0,1} with ?, because they are equivalent.
This will result in two capturing groups, one for the first name and middle initial (if it exists), and one for the last name.
I'm not sure if you want this way, but there is a method of doing it without regular expressions.
If the name is in the form of Name Name then you could do this:
// fullName is a string that has the full name, in the form of 'Name Name'
string firstName = fullName.Split(' ')[0];
string lastName = fullName.Split(' ')[1];
And if the name is in the form of Name MIName then you can do this:
string firstName = fullName.Split('.')[0] + ".";
string lastName = fullName.Split('.')[1].Trim();
Hope this helps!
Just put the optional part in the first capturing group:
(?i)^([a-z]+(?:\s[a-z]\.?)?)\s([a-z'-]+)$

How to split E-mail address from a text?

In a text box, I keep E-mail addresses.
for example
Text_box.value="a#hotmail.com,b#hotmail.com,c#hotmail.com"
How can I split all of the email addresses? Should I use Regex?
Finally, I want to keep any E-mail address which is correctly coded by user
string[] s=Text_box.Text.split(',');
Regex R=new Regex("\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b");
var temp=from t in s where R.IsMatch(t) select t;
List<string> final=new List<string>();
final.addrange(temp);
use this
string[] emails = list.Split(new char[]{','});
This will only print the matched email address and not which does not match.
private void Match()
{
Regex validationExpression = new Regex(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
string text = "whatever#gmail;a#hotmail.com,gmail#sync,b#hotmail.com,c#hotmail.com,what,dhinesh#c";
MatchCollection matchCollection = validationExpression.Matches(text);
foreach (var matchedEmailAddress in matchCollection)
{
Console.WriteLine(matchedEmailAddress.ToString());
}
Console.ReadLine();
}
This will print
a#hotmail.com
b#hotmail.com
c#hotmail.com
Other things will not be matched by regular expression.
"a#hotmail.com,b#hotmail.com,c#hotmail.com".Split(',');
There are two ways to split string.
1) Every string type object has method called Split() which takes array of characters or array of strings. Elements of this array are used to split given string.
string[] parts = Text_box.value.Split(new char[] {','});
2) Although string.Split() is enough in this example, we can achieve same result using regular expressions. Regex to split is :
string[] parts = Regex.Split(Text_box.value,#",");
You have to use correct regexp to find all forms of email adresses (with latin letters).
Check on wikipedia ( http://en.wikipedia.org/wiki/Email_address ) for correct syntax of email address (easier way) or in RFC5322, 5321 (much harder to understand).
I'm using this:
(?:[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*|""(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*"")#(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-zA-Z0-9-]*[a-zA-Z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Categories