Find exact match inside a string - c#

I want to find an exact match for a word. This is similar to what I'm using:
string TheSearchString = "John";
ContactFirst.IndexOf(TheSearchString, StringComparison.CurrentCultureIgnoreCase);
The problem is that if ContactFirst is "Johnson" then this will return a match. What's the correct way of solving this? Basically, I'm looking for a solution that doesn't return a positive for Johnson or Johnny, only when it's John or John Doe

I find using regex in conditions similar to this easier.
string ContactFirst = "sometext Johnson text";
string TheSearchString = "John";
var match = Regex.IsMatch(ContactFirst, $#"\b{TheSearchString}\b", RegexOptions.IgnoreCase) );

I'm not sure I understand correctly. if you want to compare two strings one by one can be use string method Equals
string TheSearchString = "John";
bool result = ContactFirst.Equals(TheSearchString , StringComparison.Ordinal);
if you want to get string in content
private string GetStringOnContent(string content, string searchText)
{
string findValue = string.Empty;
int strIndex = content.IndexOf(searchText);
if(strIndex > 0 )
{
findValue = content.Substring(strIndex, searchText.Length );
}
return findValue;
}
var findStr = GetStringOnContent("This is content that has John as a part of content", "John");
if you contains searchText return this , else return String.Emty

// using System.Text.RegularExpressions;
string TheSearchString = "John";
string ContactFirst = "Johnson";
// any number of whitespaces around the searched-pattern permitted but no other characters
string pattern1 = #"^[ \t\r\n]*\b" + TheSearchString + #"\b[ \t\r\n]*$";
// exactly the searched-pattern with no surrounding whitespace permitted (same as equals)
string pattern2 = #"^\b" + TheSearchString + #"\b$";
// the searched-pattern as a stand-alone word anywhere
string pattern3 = #"\b" + TheSearchString + #"\b";
Regex r = new Regex(pattern3, RegexOptions.IgnoreCase);
bool result = r.IsMatch(ContactFirst);
int foundAt = -1;
// the string index of the first match from the Matches collection
if (result)
foundAt = r.Matches(ContactFirst)[0].Index;

Related

Remove characters from a specific index character

I would like to know how can i remove characters in a string from a specific index like :
string str = "this/is/an/example"
I want to remove all characters from the third '/' including so it would be like this:
str = "this/is/an"
I tried with substring and regex but i cant find a solution.
Using string operations:
str = str.Substring(0, str.IndexOf('/', str.IndexOf('/', str.IndexOf('/') + 1) + 1));
Using regex:
str = Regex.Replace(str, #"^(([^/]*/){2}[^/]*)/.*$", "$1");
To get "this/is/an":
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/'));
If you need to keep the slash:
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/')+1);
This expects there to be at least one slash. If none are present, you should check it beforehand to not throw an exception:
string str = "this.s.an.example";
string newStr = str;
if (str.Contains('/'))
newStr = str.Remove(str.LastIndexOf('/'));
If its importaint to get the third one, make a dynamic method for it, like this. Input the string, and which "folder" you want returned. 3 in your example will return "this/is/an":
static string ReturnNdir(string sDir, int n)
{
while (sDir.Count(s => s == '/') > n - 1)
sDir = sDir.Remove(sDir.LastIndexOf('/'));
return sDir;
}
This regex is the answer: ^[^/]*\/[^/]*\/[^/]*. It will capture the first three chunks.
var regex = new Regex("^[^/]*\\/[^/]*\\/[^/]*", RegexOptions.Compiled);
var value = regex.Match(str).Value;
I think the best way of doing that it's creating a extension
string str = "this/is/an/example";
str = str.RemoveLastWord();
//specifying a character
string str2 = "this.is.an.example";
str2 = str2.RemoveLastWord(".");
With this static class:
public static class StringExtension
{
public static string RemoveLastWord(this string value, string separator = "")
{
if (string.IsNullOrWhiteSpace(value))
return string.Empty;
if (string.IsNullOrWhiteSpace(separator))
separator = "/";
var words = value.Split(Char.Parse(separator));
if (words.Length == 1)
return value;
value = string.Join(separator, words.Take(words.Length - 1));
return value;
}
}

How do I delete the values in between the tags?

I want to delete the values inside the tags, how can I do that? the highlighted output is what I want to delete when I load the save the file.
<data name="Enrolment_Exit_Verify_Message" d2p1:space="preserve" xmlns:d2p1="http://www.w3.org/XML/1998/namespace">
<value**>**Are you sure you want to Exit without Saving?****</value>
<comment>[Font]**Italic**[/Font][DateStamp]2015/02/01 00:00:00[/DateStamp][Comment] **this is a My awesome new comments comment.!!**[/Comment]</comment>
Here is how I have read in between the tags? I don't know how can I delete in-between the tags.
for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
{
string comment = oDataSet.Tables["data"].Rows[i][2].ToString();
string font = Between(comment, "[Font]", "[/Font]");
string datestamp = Between(comment, "[DateStamp]", "[/DateStamp]");
string commentVal = Between(comment, "[Comment]", "[/Comment]");
string[] row = new string[]
{
oDataSet.Tables["data"].Rows[i][0].ToString(),
oDataSet.Tables["data"].Rows[i][1].ToString(),
font,
datestamp, commentVal };
Gridview_Output.Rows.Add(row);
}
oDataSet.Tables.Add(oDataTable);
string function
public string Between(string STR, string FirstString, string LastString)
{
string FinalString;
int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
int Pos2 = STR.IndexOf(LastString);
FinalString = STR.Substring(Pos1, Pos2 - Pos1);
return FinalString;
}
You can go with the regex in your between method if you can build up the regex. Here is more info on the regex
public string Between(string STR, string FirstString, string LastString)
{
string regularExpressionPattern1 = #"(?:\" + FirstString + #")([^[]+)\[\/" + LastString;
Regex regex = new Regex(regularExpressionPattern1, RegexOptions.Singleline);
MatchCollection collection = regex.Matches(STR.ToString());
var val = string.Empty;
foreach (Match m in collection)
{
val = m.Groups[1].Value;
}
return val;
}
Note- Code is not tested may need to tweak for your need . Althoguh regex expression is tested.
Here is working fiddle for regex
The above code give you the values from the tags in you r case after executing the functions the variables will have the values
font = "**Italic**"
datestamp = "2015/02/01 00:00:00"
commentVal = "**this is a My awesome new comments comment.!!**"
Then if you want it to remove from the comment variable just use Replaceas
comment = comment.Replace(font,string.Empty);
comment = comment.Replace(datestamp ,string.Empty);
comment = comment.Replace(commentVal ,string.Empty);
At the end of it you will have the comment variable with removed values from that tags.
To delete the values in between you can modify the regular expression provided by #Coder of Code as shown below:
string str = "[Font]**Italic**[/Font][DateStamp]2015/02/01 00:00:00[/DateStamp][Comment] **this is a My awesome new comments comment.!!**[/Comment]";
string strPattern = #"(?:])([^[]+)\["; // Regular expression pattern to find string inside ][
Regex rg = new Regex(strPattern);
string newStr = rg.Replace(str, string.Format("]{0}[",string.Empty), int.MaxValue);

How to replace email address with name in text using regular expressions in C#?

how can I replace the email addresses in a paragraph assuming it's a string now, with names ?
like xx#yahoo.com.my = xx , .com, .ae
Input = "contact abc#yahoo.com or defg#hotmail.eu for more details"
Output = "contact Abc or Defg for more details"
Since you're asking for a Regex, I'm going to give you one.
Regex regex = new Regex(#"(\.|[a-z]|[A-Z]|[0-9])*#(\.|[a-z]|[A-Z]|[0-9])*");
foreach (Match match in regex.Matches(inputString))
{
// match.Value == "xx#yahoo.com.my"
string name = match.Groups[1]; // "xx"
string domain = match.Groups[2]; // "yahoo.com.my"
}
int end = myString.IndexOf('#');
string name=myString.Substring(0, end);
Try like this.
You can refer substring function here>>
http://www.dotnetperls.com/substring
Sting input = "contact abc#yahoo.com or defg#hotmail.eu for more details";
String pattern = #"(\S*)#\S*\.\S*";
String result = Regex.Replace(input , pattern , "$1");
public static string ReplaceEmail(string emailBody) {
string scrubbedemailBody = emailBody;
Regex regex = new Regex(#"(\.|[a-z]|[A-Z]|[0-9])*#(\.|[a-z]|[A-Z]|[0-9])*");
scrubbedemailBody = regex.Replace(scrubbedemailBody, match => {
return new string(' ', match.Length);
});
return scrubbedemailBody;
}

Retrieving string from a string which is in between two String?

i have a string Like
"Hello i want to go."
my code give "want to go."
but i need string between " i " and " to " how can i get this? my code is as below.
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
string input = "Hello i want to go.";
Regex regex = new Regex(#".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
result = match.Groups[1].Value;
}
This regex will match any 'word' between 'i' (not case sensitive) and 'to'.
EDIT: changed ...to.* => to\s.* as suggested in the comments.
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
If you want the word after the "i" then:
string result = input.Split(" i ")[1].Split(" ")[0];
Use
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
just do it with one simple line of code
var word = "Hello i want to go.".Split(' ')[2];
//Returns the word "want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
Here's an example using Regex which gives you the index of each occurrence of "want":
string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");
while(match.Success){
Console.WriteLine(string.Format("Index: {0}", match.Index));
match = match.NextMatch();
}
Nowhere does it say Regex...
string result = input.Split.Skip(2).Take(1).First()
it's work
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
and it can be called as
string respons = Between("Hello i want to go."," i "," to ");
it return want

Using LINQ to strip a suffix from a string if it contains a suffix in a list?

How can I strip a suffix from a string, and return it, using C#/LINQ? Example:
string[] suffixes = { "Plural", "Singular", "Something", "SomethingElse" };
string myString = "DeleteItemMessagePlural";
string stringWithoutSuffix = myString.???; // what do I do here?
// stringWithoutSuffix == "DeleteItemMessage"
var firstMatchingSuffix = suffixes.Where(myString.EndsWith).FirstOrDefault();
if (firstMatchingSuffix != null)
myString = myString.Substring(0, myString.LastIndexOf(firstMatchingSuffix));
You need to build a regular expression from the list:
var regex = new Regex("(" + String.Join("|", list.Select(Regex.Escape)) + ")$");
string stringWithoutSuffix = regex.Replace(myString, "");
// Assuming there is exactly one matching suffix (this will check that)
var suffixToStrip = suffixes.Single(x => myString.EndsWith(x));
// Replace the matching one:
var stringWithoutSuffix = Regex.Replace(myString, "(" +suffixToStrip + ")$", "");
OR, since you know the length of the matching suffix:
// Assuming there is exactly one matching suffix (this will check that)
int trim = suffixes.Single(x => myString.EndsWith(x)).Length;
// Remove the matching one:
var stringWithoutSuffix = myString.Substring(0, myString.Length - trim);

Categories

Resources