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
Related
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;
I do want to get all the text before the first \r\n\ symbol. For example,
lalal lalal laldlasdaa daslda\r\n\Prefersaasda reanreainrea
I would need: lalal lalal laldlasdaa daslda. The above string can be empty, but it also may not contain any '\r\n\' symbol." How can I achieve this?
You can use IndexOf to get the position, then use Substring to get the first part:
string s = "lalal lalal laldlasdaa daslda\r\n Prefersaasda reanreainrea";
int positionOfNewLine = s.IndexOf("\r\n");
if (positionOfNewLine >= 0)
{
string partBefore = s.Substring(0, positionOfNewLine);
}
Hope that this is what you are looking for:
string inputStr = "lalal lalal laldlasdaa daslda\r\nPrefersaasda reanreainrea";
int newLineIndex = inputStr.IndexOf("\r\n");
if(newLineIndex != -1)
{
string outPutStr = inputStr.Substring(0, newLineIndex );
// Continue
}
else
{
// Display message no new line character
}
Checkout an example here
You can use Split like this
string mystring = #"lalal lalal laldlasdaa daslda\r\n\Prefersaasda reanreainrea";
string mylines = mystring.Split(new string[] { #"\r\n" }, StringSplitOptions.None)[0];
Whereas if the string is like
string mystring = "lalal lalal laldlasdaa daslda\r\n Prefersaasda reanreainrea";
string mylines = mystring.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[0];
Environment.NewLine will also work with it. The with \r\n\P is making that string an invalid string thus \r\n P makes it a new line
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;
}
}
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 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;
}