Example String
This is an important example about regex for my work.
I can extract important example about regex with this (?<=an).*?(?=for) snippet. Reference
But i would like to extract to string right to left side. According to this question's example; first position must be (for) second position must be (an).
I mean extracting process works back ways.
I tried what i want do as below codes in else İf case, but it doesn't work.
public string FnExtractString(string _QsString, string _QsStart, string _QsEnd, string _QsWay = "LR")
{
if (_QsWay == "LR")
return Regex.Match(_QsString, #"(?<=" + _QsStart + ").*?(?=" + _QsEnd + ")").Value;
else if (_QsWay == "RL")
return Regex.Match(_QsString, #"(?=" + _QsStart + ").*?(<=" + _QsEnd + ")").Value;
else
return _QsString;
}
Thanks in advance.
EDIT
My real example as below
#Var|First String|ID_303#Var|Second String|ID_304#Var|Third String|DI_t55
When i pass two string to my method (for example "|ID_304" and "#Var|") I would like to extract "Second String" but this example is little peace of my real string and my string is changeable.
No need for forward or backward lookahead! You could just:
(.*)\san\s.*\sfor\s
The \s demands whitespace, so you don't match an import*an*t.
One potential problem in your current solution is that the string passed in contains special characters, which needs to be escaped with Regex.Escape before concatenation:
return Regex.Match(_QsString, #"(?<=" + Regex.Escape(_QsStart) + ").*?(?=" + Regex.Escape(_QsEnd) + ")").Value;
For your other requirement of matching RL, I don't understand your requirement.
Related
Morning folks,
I have an ASP.Net C# page that pulls in a list of servers from a SQL box and displays the list of servers in a label. ("srv1,srv2,srv3"). I need to add double quotes around each of the servers names. ("srv1","srv2","srv3",)
Any help would be greatly appreached.
If you have string
string str = "srv1,srv2,srv3";
Then you can simply do
str = "\"" + str.Replace(",", "\",\"") + "\"";
Now str contains "srv1","srv2","srv3"
As far as I can understand, you are trying to use double quotes in a string.
If you want to use such,
you can use escape character:
("\"srv1\",\"srv2\",\"srv3\"",)
for the sake of simplicity, you can even convert it to a function:
private string quoteString(string serverName){
return "\"" + serverName + "\"";
}
Also, if you have already "srv1,srv2,srv3" format, find ',' characters in the string and add " before and after comma. Also, notice that you should add to first index and last index ".
I'm currently trying to strip a string of data that is may contain the hyphen symbol.
E.g. Basic logic:
string stringin = "test - 9894"; OR Data could be == "test";
if (string contains a hyphen "-"){
Strip stringin;
output would be "test" deleting from the hyphen.
}
Console.WriteLine(stringin);
The current C# code i'm trying to get to work is shown below:
string Details = "hsh4a - 8989";
var regexItem = new Regex("^[^-]*-?[^-]*$");
string stringin;
stringin = Details.ToString();
if (regexItem.IsMatch(stringin)) {
stringin = stringin.Substring(0, stringin.IndexOf("-") - 1); //Strip from the ending chars and - once - is hit.
}
Details = stringin;
Console.WriteLine(Details);
But pulls in an Error when the string does not contain any hyphen's.
How about just doing this?
stringin.Split('-')[0].Trim();
You could even specify the maximum number of substrings using overloaded Split constructor.
stringin.Split('-', 1)[0].Trim();
Your regex is asking for "zero or one repetition of -", which means that it matches even if your input does NOT contain a hyphen. Thereafter you do this
stringin.Substring(0, stringin.IndexOf("-") - 1)
Which gives an index out of range exception (There is no hyphen to find).
Make a simple change to your regex and it works with or without - ask for "one or more hyphens":
var regexItem = new Regex("^[^-]*-+[^-]*$");
here -------------------------^
It seems that you want the (sub)string starting from the dash ('-') if original one contains '-' or the original string if doesn't have dash.
If it's your case:
String Details = "hsh4a - 8989";
Details = Details.Substring(Details.IndexOf('-') + 1);
I wouldn't use regex for this case if I were you, it makes the solution much more complex than it can be.
For string I am sure will have no more than a couple of dashes I would use this code, because it is one liner and very simple:
string str= entryString.Split(new [] {'-'}, StringSplitOptions.RemoveEmptyEntries)[0];
If you know that a string might contain high amount of dashes, it is not recommended to use this approach - it will create high amount of different strings, although you are looking just for the first one. So, the solution would look like something like this code:
int firstDashIndex = entryString.IndexOf("-");
string str = firstDashIndex > -1? entryString.Substring(0, firstDashIndex) : entryString;
you don't need a regex for this. A simple IndexOf function will give you the index of the hyphen, then you can clean it up from there.
This is also a great place to start writing unit tests as well. They are very good for stuff like this.
Here's what the code could look like :
string inputString = "ho-something";
string outPutString = inputString;
var hyphenIndex = inputString.IndexOf('-');
if (hyphenIndex > -1)
{
outPutString = inputString.Substring(0, hyphenIndex);
}
return outPutString;
I want to split a string only at last occurrence of special character.
I try to parse a name of a tab from browser, so my initial string looks for example like this:
Untitled - Google Chrome
That is easy to solve as there is a Split function. Here is my implementation:
var pageparts= Regex.Split(inputWindow.ToString(), " - ");
InsertWindowName(pageparts[0].ToString(), pageparts[1].ToString());//method to save string into separate columns in DB
This works, but problem occurs, when I get a page like this:
SQL injection - Wikipedia, the free encyclopedia - Mozilla Firefox
Here are two dashes, which means, that after split is done, there are 3 separate strings in array and if I would continue normally, database would contain in first column value "SQL injection" and in second column value "Wikipedia, the free encyclopedia". Last value will be completely left out.
What I want is that first column in database will have value:
SQL injection - Wikipedia, the free encyclopedia" and second column will have:
"Mozilla Firefox". Is that somehow possible?
I tried to use a Split(" - ").Last() function (even LastOrDefault() too), but then I only got a last string. I need to get both side of the original string. Just separated by last dash.
You can use String.Substring with String.LastIndexOf:
string str = "SQL injection - Wikipedia, the free encyclopedia - Mozilla Firefox";
int lastIndex = str.LastIndexOf('-');
if (lastIndex + 1 < str.Length)
{
string firstPart = str.Substring(0, lastIndex);
string secondPart = str.Substring(lastIndex + 1);
}
Create a extension method (or a simple method) to perform that operation and also add some error checking for lastIndex.
EDIT:
If you want to split on " - " (space-space) then use following to calculate lastIndex
string str = "FirstPart - Mozzila Firefox-somethingWithoutSpace";
string delimiter = " - ";
int lastIndex = str.LastIndexOf(delimiter);
if (lastIndex + delimiter.Length < str.Length)
{
string firstPart = str.Substring(0, lastIndex);
string secondPart = str.Substring(lastIndex + delimiter.Length);
}
So for string like:
"FirstPart - Mozzila Firefox-somethingWithoutSpace"
Output would be:
FirstPart
Mozzila Firefox-somethingWithoutSpace
Please forgive me for my laziness ins this solution i'm sure there is a better approach but i will give you one solution proposal i'm assuming you are codding in C#.
First of all correct me if I get wrongly the question no matter what you just want to columns returned the first (all text even of it includes dashes but the last one) and last column (all the text after last dash) if it's ok. let's do it.
// I Only use split function when I want all data in separate variable (array position) in you case I assumed that you just want 2 values (if possible), so you can use substring.
static void Main(string[] args)
{
string firstname = "";
string lastName = "";
string variablewithdata = "SQL injection - Wikipedia, -the free encyclopedia - Mozilla Firefox";
// variablewithdata.LastIndexOf('-') = returns Integer corresponding to the last position of that character.
//I suggest you validate if variablewithdata.LastIndexOf('-') is equal to -1 or not because if it don't found your character it returns -1 so if the value isn't -1 you can substring
firstname = variablewithdata.Substring(0, (variablewithdata.LastIndexOf('-') - 1));
lastName = variablewithdata.Substring(variablewithdata.LastIndexOf('-') + 1);
Console.WriteLine("FirstColumn: {0} \nLastColumn:{1}",firstname,lastName);
Console.ReadLine();
}
If it's not what you want can you explain me for example for "SQL injection - Wikipedia,- the free - encyclopedia - Mozilla Firefox" what's suppose to be returned?
Forgive me for unclean code i'm bored today.
If you don't care about reassembling strings, you could use something like :
var pageparts= Regex.Split(inputWindow.ToString(), " - ");
var firstPart = string.Join(" - ", pageparts.Take(pageparts.Length - 1));
var secondPart = pageparts.Last()
InsertWindowName(firstPart, secondPart);
I am trying to remove all of a specific character from a string. I have been using String.Replace, but it does nothing, and I don't know why. This is my current code:
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
This just leaves the string as it was before. Can anyone please explain to me as to why?
You must assign the return value of String.Replace to your original string instance:
hence instead of(no need for the Contains check)
if (Gamertag2.Contains("^"))
{
Gamertag2.Replace("^" + 1, "");
}
just this(what's that mystic +1?):
Gamertag2 = Gamertag2.Replace("^", "");
Two things:
1) C# Strings are immutable. You'll need to do this :
Gamertag2 = Gamertag2.Replace("^" + 1, "");
2) "^" + 1? Why are you doing this? You are basically saying Gamertag2.Replace("^1", ""); which I'm sure is not what you want.
Like climbage said, your problem is definitely
Gamertag2.Replace("^"+1,"");
That line will only remove instances of "^1" from your string. If you want to remove all instances of "^", what you want is:
Gamertag2.Replace("^","");
I know this thread is old and also that my solution may be inefficient to the extreme, but it replaces all occurrences of a string. Found that if I was looking for "\r\n\r\n\r\n" to replace with "\r\n\r\n" a single Replace() didn't catch all.
Therefor this:
do // First get rid of spaces like " \r"
{
str = str.Replace(" \r","\r")
} while (str.Cointains(" \r"));
do // Then remove the CrLf's in surplus.
{
str = str.Replace("\r\n\r\n\r\n","\r\n\r\n")
} while (str.Cointains("\r\n\r\n\r\n"));
If I have a string such as the following:
String myString = "SET(someRandomName, \"hi\", u)";
where I know that "SET(" will always exists in the string, but the length of "someRandomName" is unknown, how would I go about deleting all the characters from "(" to the first instance of """? So to re-iterate, I would like to delete this substring: "SET(someRandomName, \"" from myString.
How would I do this in C#.Net?
EDIT: I don't want to use regex for this.
Providing the string will always have this structure, the easiest is to use String.IndexOf() to look-up the index of the first occurence of ". String.Substring() then gives you appropriate portion of the original string.
Likewise you can use String.LastIndexOf() to find the index of the first " from the end of the string. Then you will be able to extract just the value of the second argument ("hi" in your sample).
You will end up with something like this:
int begin = myString.IndexOf('"');
int end = myString.LastIndexOf('"');
string secondArg = myString.Substring(begin, end - begin + 1);
This will yield "\"hi\"" in secondArg.
UPDATE: To remove a portion of the string, use the String.Remove() method:
int begin = myString.IndexOf('(');
int end = myString.IndexOf('"');
string altered = myString.Remove(begin + 1, end - begin - 1);
This will yield "SET(\"hi\", u)" in altered.
I know it's been years, but .Net been has also evolved in the meantime.
Consider using range operator in case anyone looking here for an answer.
Assuming that Set( and \"hi\", u) is constant value (8 digit without the escapes):
var sub = myString[^4...^8];
myString.Replace(sub, replaceValue);
more examples and a good explanation in this article or of course in microsoft docs
This is pretty awful, but this will accomplish what you want with a simple linq statement. Just presenting as an alternative to the IndexOf answers.
string myString = "SET(someRandomName, \"hi\", 0)";
string fixedStr = new String( myString.ToCharArray().Take( 4 ).Concat( myString.ToCharArray().SkipWhile( c => c != '"' ) ).ToArray() );
yields: SET("hi", 0)
Note: the skip is hard-coded for 4 characters, you could alter it to skip over the characters in an array that contains them instead.
I assume you want to transform
SET(someRandomName, "hi", u)
into:
SET(u)
To achieve that, you can use:
String newString = "SET(" + myString.Substring(myString.LastIndexOf(',') + 1).Trim();
To explain this bit by bit:
myString.LastIndexOf(',')
will give you the index (position) of your last , character. Increment it by 1 to get the start index of the third argument in your SET function.
myString.Substring(myString.LastIndexOf(',') + 1)
The Substring method will eliminate all characters up to the specified position. In this case, we’re eliminating everything up to (and including) the last ,. In the example above, this would eliminate the SET(someRandomName, "hi", part, and leave us with u).
The Trim is necessary simply to remove the leading space character before your u.
Finally, we prepend SET( to our substring (since we had formerly removed it due to our Substring).
Edit: Based on your comment below (which contradicts what you asked in your question), you can use:
String newString = "SET(" + myString.Substring(myString.IndexOf(',') + 1).Trim();