My input is going to be as follows:
abc#gmail.com,def#yahoo.com;xyz#gmail.com;ghi#hotmail.com and so on
Now I want my output to be:
abc
def
xyz
ghi
The following is my code:
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main(string[] args)
{
string str;
string[] newstr,newstr2;
Console.WriteLine("Enter the email addresses: ");
str=Console.ReadLine();
newstr=Regex.Split(str,",|;|#");
foreach (string s in newstr)
{
Console.WriteLine(s);
}
}
}
My output right now is:
abc
gmail.com
def
yahoo.com
xyz
gmail.com
ghi
hotmail.com
Any kind of help would be greatly appreciated. Thanks.
You shouldn't use regex for split, and should no split by #. Instead, use the follopwing code:
using System;
public class Program
{
public static void Main(string[] args)
{
string str;
string[] newstr;
Console.WriteLine("Enter the email addresses: ");
str = Console.ReadLine();
newstr = str.Split(new char[] { ',', ';' }); // Split to get a temporal array of addresses
foreach (string s in newstr)
{
Console.WriteLine(s.Substring(0, s.IndexOf('#'))); // Extract the sender from the email addresses
}
}
}
Edit:
Or, with LINQ:
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args)
{
string str;
string[] newstr;
Console.WriteLine("Enter the email addresses: ");
str = Console.ReadLine();
newstr = str.Split(new char[] { ',', ';' }) // Split to get a array of addresses to work with
.Select(s => s.Substring(0, s.IndexOf('#'))).ToArray(); // Extract the sender from the email addresses
foreach (string s in newstr)
{
Console.WriteLine(s);
}
}
}
another approach without RegEx
string input = "abc#gmail.com,def#yahoo.com;xy#gmail.com; ghi#hotmail.com";
var result = input.Split(',', ';').Select(x => x.Split('#').First());
first Split the adresses by , and ;, then select the part before the # by splitting again.
You can use this email regex:
var regex = new Regex(#"(?<name>\w+([-+.']\w+)*)#\w+([-.]\w+)*\.\w+([-.]\w+)*");
var results =
regex.Matches("abc#gmail.com,def#yahoo.com;xyz#gmail.com;ghi#hotmail.com")
.Cast<Match>()
.Select(m => m.Groups["name"].Value)
.ToList();
Perhaps using this might help
str.Substring(0, str.LastIndexOf(" ")<0?0:str.LastIndexOf(" "));
As Mail is a weird thing with a complexe definition, I will never assume that something with an # is a mail.
My best try would be to convert the string to a MailAddress, just in case it look like a mail but it's not one because of some invalid char etc.
string input = "abc#gmail.com,ghi#hotmail.com;notme; #op this is not a mail!";
var result = input
.Split(',', ';') // Split
.Select(x =>
{
string adr = "";
try
{ // Create an MailAddress, MailAddress has no TryParse.
adr = new MailAddress(x).User;
}
catch
{
return new { isValid = false, mail = adr };
}
return new { isValid = true, mail = adr };
})
.Where(x => x.isValid)
.Select(x => x.mail);
Actually, in the regular expression, to capture some substring, you need to wrap the expected content by ( and )
Below code should work
string str22 = "abc#gmail.com;def#yahoo.com,xyz#gmail.com;fah#yao.com,h347.2162#yahoo.com.hk";// ghi#hotmail.com";
List<string> ret = new List<string>();
string regExp = #"(.*?)#.*?[,;]{1}|(.*)#";
MatchCollection matches = Regex.Matches(str22, regExp, RegexOptions.IgnoreCase);
foreach (Match match in matches)
{
if (match.Success)
{
int pvt = 1;
while (string.IsNullOrEmpty(match.Groups[pvt].Value))
{
pvt++;
}
MessageBox.Show(match.Groups[pvt].Value);
}
}
return;
The regular expression is as below
(.*?)#.*?[,;]{1}|(.*)#
(.*?)#.*?[,;]{1} is fetching the substring before # and ? restrict it fetches the first match.
The last email do not contain , or ;, thus add a OR condition and fetch the last email name by the substring before #
Related
I have a code for conversion but some address have different result to what is expected.
23 Starling St => 3 Streetarling Street which is wrong and it should be 23 Starling Street
1 St Johns Ct => 1 Street Johns Ct => Correct
This is the code:
private string StreetConversion(string address, Order order)
{
string[] addressList = address.Split(' ');
foreach (string add in addressList)
{
if(add == "pde")
address = address.Replace("pde", "Parade");
if (add == "Pde")
address = address.Replace("Pde", "Parade");
if (add == "Rd")
address = address.Replace("Rd", "Road");
if (add == "rd")
address = address.Replace("rd", "Road");
if (add == "St")
address = address.Replace("St", "Street");
if (add == "st")
address = address.Replace("st", "Street");
}
order.ShipAddress1 = address;
return address;
}
You need to replace given word instead of replacing all occurences of that word in address variable,
private string StreetConversion(string address, Order order)
{
string[] addressList = address.Split(' ');
StringBuilder newAddress = new StringBuilder();
foreach (string add in addressList)
{
if(add.ToLower() == "pde")
newAddress.Append("Parade ");
else if (add.ToLower() == "rd")
newAddress.Append("Road ");
else if (add.ToLower() == "st")
newAddress.Append("Street ");
else
newAddress.Append(add+ " ");
}
order.ShipAddress1 = newAddress.ToString();
return newAddress.ToString();
}
First of all, let's extract model: acronyms and their substitutions
private static Dictionary<string, string> acronyms =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{"pde", "Parade"},
{"rd", "Road"},
{"st", "Street"},
//TODO: Add more pairs if required, say, {"sq", "square"},
};
Then we can easily transform the string address:
using System.Linq;
...
private string StreetConversion(string address, Order order) {
string result = string.Join(" ", address
.Split(' ')
.Select(word => acronyms.TryGetValue(word, out var newWord) ? newWord : word));
order.ShipAddress1 = result;
return result;
}
Step 1: Lets follow "The Single Responsibility Principle" to keep code cleaner and maintainable.
"The Single Responsibility Principle: A class or method should have only a single responsibility."
So you need to take out the following code from the method:
order.ShipAddress1 = address;
Step 2: Your method responsibility should only be converting the street and return it back, and you can reach that in many ways, the following is one of the ways:
private string StreetConversion(string address) {
var newAddress= string.Empty;
foreach (var s in address.Split(' ')) {
newAddress+= (s.ToLower()) switch {
"st" => "Street",
"rd" => "Road",
"pde" => "Parade",
_ => s + " ",
};
}
return newAddress;
}
Step 3: Calling the method
order.ShipAddress1 = StreetConversion(OldAddress);
You can use Regex also to replace the work with another word.
s = Regex.Replace(s, #"\boldVal1\b", "newVal1", RegexOptions.IgnoreCase);
s = Regex.Replace(s, #"\boldVal2\b", "newVal2", RegexOptions.IgnoreCase);
I am new to RegEx. I have a string like following. I want to get the values between [{# #}]
Ex: "Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]"
I would like to get the following values from the above string.
"John",
"ABC Bank",
"Houston"
Based on the solution Regular Expression Groups in C#.
You can try this:
string sentence = "Employee name is [{#john#}], works for [{#ABC BANK#}],
[{#Houston#}]";
string pattern = #"\[\{\#(.*?)\#\}\]";
foreach (Match match in Regex.Matches(sentence, pattern))
{
if (match.Success && match.Groups.Count > 0)
{
var text = match.Groups[1].Value;
Console.WriteLine(text);
}
}
Console.ReadLine();
Based on the solution and awesome breakdown for matching patterns inside wrapping patterns you could try:
\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]
Where \[\{\# is your escaped opening sequence of [{# and \#\}\] is the escaped closing sequence of #}].
Your inner values are in the matching group named Text.
string strRegex = #"\[\{\#(?<Text>(?:(?!\#\}\]).)*)\#\}\]";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
string strTargetString = #"Employee name is [{#John#}], works for [{#ABC Bank#}], [{#Houston#}]";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
var text = myMatch.Groups["Text"].Value;
// TODO: Do something with it.
}
}
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Test("the quick brown [{#fox#}] jumps over the lazy dog."));
Console.ReadLine();
}
public static string Test(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
var result = System.Text.RegularExpressions.Regex.Replace(str, #".*\[{#", string.Empty, RegexOptions.Singleline);
result = System.Text.RegularExpressions.Regex.Replace(result, #"\#}].*", string.Empty, RegexOptions.Singleline);
return result;
}
}
}
i need to split a string in C# .net.
output i am getting : i:0#.f|membership|sdp950452#abctechnologies.com or i:0#.f|membership|tss954652#abctechnologies.com
I need to remove i:0#.f|membership| and #abctechnologies.com from the string. out put i need is sdp950452 or tss954652
also one more string I am getting is Pawar, Jaywardhan and i need it to be jaywardhan pawar
thanks,
Jay
Here is code example how you can do first part with Regex and the second with Splits and Replaces:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
public class Program
{
public static void Main()
{
//First part
string first = "i:0#.f|membership|sdp950452#abctechnologies.com";
string second = "i:0#.f|membership|tss954652#abctechnologies.com";
string pattern = #"\|[A-Za-z0-9]+\#";
Regex reg = new Regex(pattern);
Match m1 = reg.Match(first);
Match m2 = reg.Match(second);
string result1 = m1.Value.Replace("|",string.Empty).Replace("#",string.Empty);
string result2 = m2.Value.Replace("|", string.Empty).Replace("#", string.Empty);
Console.WriteLine(result1);
Console.WriteLine(result2);
//Second part
string inputString = "Pawar, Jaywardhan";
string a = inputString.ToLower();
var b = a.Split(' ');
var result3 = b[1] + " " + b[0].Replace(",",string.Empty);
}
}
}
Using Linq to reduce the code lines
Link to dotnetfiddle code sample
using System.Linq;
using System;
public class Program
{
public static void Main()
{
//Extract email
string a = "i:0#.f|membership|sdp950452#abctechnologies.com";
string s = a.Split('|').Where(splitted => splitted.Contains("#")).FirstOrDefault().Split('#').First();
Console.WriteLine(s);
//Format Name
string name = "Pawar, Jaywardhan";
string formatted = String.Join(" ",name.Split(',').Reverse()).ToLower().TrimStart().TrimEnd();
Console.WriteLine(formatted);
}
}
I have a string
"[\"1,1\",\"2,2\"]"
and I want to turn this string onto this
1,1,2,2
I am using Replace function for that like
obj.str.Replace("[","").Replace("]","").Replace("\\","");
But it does not return the expected result.
Please help.
You haven't removed the double quotes. Use the following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");
Here is an optimized approach in case the string or the list of exclude-characters is long:
public static class StringExtensions
{
public static String RemoveAll(this string input, params Char[] charactersToRemove)
{
if(string.IsNullOrEmpty(input) || (charactersToRemove==null || charactersToRemove.Length==0))
return input;
var exclude = new HashSet<Char>(charactersToRemove); // removes duplicates and has constant lookup time
var sb = new StringBuilder(input.Length);
foreach (Char c in input)
{
if (!exclude.Contains(c))
sb.Append(c);
}
return sb.ToString();
}
}
Use it in this way:
str = str.RemoveAll('"', '[', ']', '\\');
// or use a string as "remove-array":
string removeChars = "\"{[]\\";
str = str.RemoveAll(removeChars.ToCharArray());
You should do following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\"","");
string.Replace method does not replace string content in place. This means that if you have
string test = "12345" and do
test.Replace("2", "1");
test string will still be "12345". Replace doesn't change string itself, but creates new string with replaced content. So you need to assign this new string to a new or same variable
changedTest = test.Replace("2", "1");
Now, changedTest will containt "11345".
Another note on your code is that you don't actually have \ character in your string. It's only displayed in order to escape quote character. If you want to know more about this, please read MSDN article on string literals.
how about
var exclusions = new HashSet<char>(new[] { '"', '[', ']', '\\' });
return new string(obj.str.Where(c => !exclusions.Contains(c)).ToArray());
To do it all in one sweep.
As Tim Schmelter writes, if you wanted to do it often, especially with large exclusion sets over long strings, you could make an extension like this.
public static string Strip(
this string source,
params char[] exclusions)
{
if (!exclusions.Any())
{
return source;
}
var mask = new HashSet<char>(exclusions);
var result = new StringBuilder(source.Length);
foreach (var c in source.Where(c => !mask.Contains(c)))
{
result.Append(c);
}
return result.ToString();
}
so you could do,
var result = "[\"1,1\",\"2,2\"]".Strip('"', '[', ']', '\\');
Capture the numbers only with this regular expression [0-9]+ and then concatenate the matches:
var input = "[\"1,1\",\"2,2\"]";
var regex = new Regex("[0-9]+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value);
var result = string.Join(",", matches);
I am new to programming languages. I have a requirement where I have to return a record based on a search string.
For example, take the following three records and a search string of "Cal":
University of California
Pascal Institute
California University
I've tried String.Contains, but all three are returned. If I use String.StartsWith, I get only record #3. My requirement is to return #1 and #3 in the result.
Thank you for your help.
If you're using .NET 3.5 or higher, I'd recommend using the LINQ extension methods. Check out String.Split and Enumerable.Any. Something like:
string myString = "University of California";
bool included = myString.Split(' ').Any(w => w.StartsWith("Cal"));
Split divides myString at the space characters and returns an array of strings. Any works on the array, returning true if any of the strings starts with "Cal".
If you don't want to or can't use Any, then you'll have to manually loop through the words.
string myString = "University of California";
bool included = false;
foreach (string word in myString.Split(' '))
{
if (word.StartsWith("Cal"))
{
included = true;
break;
}
}
I like this for simplicity:
if(str.StartsWith("Cal") || str.Contains(" Cal")){
//do something
}
You can try:
foreach(var str in stringInQuestion.Split(' '))
{
if(str.StartsWith("Cal"))
{
//do something
}
}
You can use Regular expressions to find the matches. Here is an example
//array of strings to check
String[] strs = {"University of California", "Pascal Institute", "California University"};
//create the regular expression to look for
Regex regex = new Regex(#"Cal\w*");
//create a list to hold the matches
List<String> myMatches = new List<String>();
//loop through the strings
foreach (String s in strs)
{ //check for a match
if (regex.Match(s).Success)
{ //add to the list
myMatches.Add(s);
}
}
//loop through the list and present the matches one at a time in a message box
foreach (String matchItem in myMatches)
{
MessageBox.Show(matchItem + " was a match");
}
string univOfCal = "University of California";
string pascalInst = "Pascal Institute";
string calUniv = "California University";
string[] arrayofStrings = new string[]
{
univOfCal, pascalInst, calUniv
};
string wordToMatch = "Cal";
foreach (string i in arrayofStrings)
{
if (i.Contains(wordToMatch)){
Console.Write(i + "\n");
}
}
Console.ReadLine();
}
var strings = new List<string> { "University of California", "Pascal Institute", "California University" };
var matches = strings.Where(s => s.Split(' ').Any(x => x.StartsWith("Cal")));
foreach (var match in matches)
{
Console.WriteLine(match);
}
Output:
University of California
California University
This is actually a good use case for regular expressions.
string[] words =
{
"University of California",
"Pascal Institute",
"California University"
}
var expr = #"\bcal";
var opts = RegexOptions.IgnoreCase;
var matches = words.Where(x =>
Regex.IsMatch(x, expr, opts)).ToArray();
The "\b" matches any word boundary (punctuation, space, etc...).