what can I use to replace the string if its in the following format
I' have a "car" that runs very well
So basically i have a search function
and if they just type ' it wasnt finding it so i did
mySearchWord.Replace("'", "''")
and then it found it but now what if there is an ' and " in the same sentence or word, how can i check for both in mySearchWord ?
because for both cases i would do something like
mySearchWord.Replace("'", "''")
mySearchWord.Replace("\"", "\"") //have no idea about this one
or something like that, is there a way to do it at once?
I think someone below is pointing me in the right direction, i just need to be able to pass apostrophes or quotation marks to my search but it was throwing an error maube because when passed, just as in sql, you would need to escape a quotation or apostrophe
This actually replaces both at once:
string text = "I' have a \"car\" that runs very well";
string pattern = "['\"]";
var result = Regex.Replace(text, pattern, m => (m.Value == "'") ? "''" : "\"\"");
I should explain.
This is using a method called Regular Expressions. The pattern variable is the regular expression pattern which is used to match things in the string text. In this case the pattern states that it should match all ' and " characters in the text. The pattern [abc] would match all a, b and c characters.
Regular Expressions seem complex at first, but is very powerful.
You find the Regex class in the System.Text.RegularExpressions namespace.
Here is the documentation for it: http://msdn.microsoft.com/en-us/library/c75he57e(v=VS.100).aspx
The code m => (m.Value == "'") ? "''" : "\"\"" is a Lambda expression, which is a short hand to the Delegate MatchEvaluator (docs).
mySearchWord.Replace("''", "[{just_to_replace}]").Replace("'", "''").Replace("[{just_to_replace}]", "''");
cool, ain't it.
Related
I have a couple of strings like:
test
test. hi
test, hello.(actual whitespace)
hello -this is a test
hello v2 , i am a " test" as well
I'd like to align punctuation following some set of rules like:
commas should have a trailing space but not a leading one
hyphens should have spaces on both sides if there is at least one space on any side of it in the original string
dots should have s trailing space aside from a case when they are on the end of the string
quotation marks (single and double) should not have spaces on opening/closing sides
etc etc (other rules will be added as needed, covering first 4 is enough for this case)
So the output will be like:
test
test. hi
test, hello.
hello - this is a test
hello v2, i am a "test" as well
My questions are: is it possible to do it in one go - with a single regex instead of creating a regex for each case, and if yes - what would be the regex that can do that? Is there a more efficient way of doing it than in a single regex (if it's possible), especially considering the fact that i'm already iterating through the whole string to remove some special unicode characters?
Using the MatchEvaluator delegate version of Regex.Replace, you can use a Regex to find problematic punctuation, and then use conditional logic to return the proper result. This doesn't handle rule 4 - it isn't easy to recognize open versus close quotes in a regular expression.
List<String> src;
var p = new Regex(#"\s*,\s*|\s+-\s*|-\s+|\s*\.\s+(?=.)", RegexOptions.Compiled);
var ans = src.Select(s => p.Replace(s, m => {
var mv = m.Value.Trim();
return mv == "," ? ", " : mv == "-" ? " - " : mv == "." ? ". " : mv;
})).ToList();
I have string expression like this
CONTAIN("A(ASDFASDF)","MAKLOON") && !CONTAIN("THIS IS THE (STRING) ","MAKLON") && !CONTAIN("ASDFASDF","MAKLUN") && ("121"=="" || 121.00=="" || 121.0=="")
I want to match only the result like this :
1. CONTAIN("A(ASDFASDF)","MAKLOON")
2. CONTAIN("THIS IS THE (STRING) ","MAKLON")
3. CONTAIN("ASDFASDF","MAKLUN")
I have try with this regex but the match only this :
CONTAIN\(.*?\)
Result
1. CONTAIN("A(ASDFASDF)
2. CONTAIN("THIS IS THE (STRING)
3. CONTAIN("ASDFASDF","MAKLUN")
How to solve my problem? Thanks
Here's a slightly enhanced version, which allows the inner string to have parenthesis. It's not perfect either, but probably a bit more secure:
CONTAIN\(".*?", ?".*?"\)
Brief explanation: It matches CONTAIN(, then any character until it finds "," or ", " (optional space, remove ? if you will never have a space there), then again any character until the final "). The ? after the * is necessary to make it match as little as possible. Otherwise, .* would match as much as possible, from the first to the last CONTAIN string.
Besides matching what you mention in your post, it will also match:
CONTAIN("HEL()LO",")WORLD(")
CONTAIN(")HELLO(",")WORLD(")
And will not match an invalid strings like these, which are matched by the other proposed solutions:
CONTAIN("HELLO",")WORLD() // partial match
CONTAIN(")
CONTAIN(""")
I tried to do some more complex regex to match the number of quotes or parenthesis, but I think you don't need such complexity, unless your string may have escaped quotes, like \" or "".
If you won't get any of those invalid strings or strange strings, you may be good enough with the other simpler regex.
You could try this pattern: CONTAIN\(.*?"\)
I think the regular expression you're looking for would be: (CONTAIN\(\".+\"\)). By including the \" you get all of the characters inside the quotes instead of ending at the first instance of a ')'.
I have this text
'Random Text', 'a\nb\\c\'d\\', 'ok'
I want it to become
'Random Text', 'a\nb\c''d\', 'ok'
The issue is escaping. Instead of escaping with \ I now escape only ' with ''. This is for a 3rd party program so I can't change it thus needing to change one escaping method to another.
The issue is \\'. If i do string replace it will become \'' rather than \'. Also \n is not a newline but the actual text \n which shouldn't be modified. I tried using regex but I couldn't think of a way to say if ' replace with '' else if \\ replace with \. Obviously doing this in two step creates the problem.
How do I replace this string properly?
If I understand your question correctly, the issue lies in replacing \\ with \, which can then cause another replacement if it occurs right before '. One technique would be to replace it to an intermediary string first that you're sure will not occur anywhere else, then replace it back after you're done.
var str = #"'Random Text', 'a\nb\\c\'d\\', 'ok'";
str.Replace(#"\\", "NON_OCCURRING_TEMP")
.Replace(#"\'", "''")
.Replace("NON_OCCURRING_TEMP", #"\");
As pointed out by #AlexeiLevenkov, you can also use Regex.Replace to do both modifications simultaneously.
Regex.Replace(str, #"(\\\\)|(\\')",
match => match.Value == #"\\" ? #"\" : #"''");
Seems voithos' interpretation of the question is the right one. Another approach is to use RegEx to find all tokens at once and replace ReguarExpression.Replace
Starting point:
var matches = new Regex(#"\\\\'|\\'|'");
Console.Write(matches.Replace(#"'a b\nc d\\e\'f\\'",
match =>"["+match + "]"));
I have an issue that I can't seem to find a solution for it. I'm using Regex.IsMatch to check if an input matches what's expected. If an input contains **, ++, it complains. For example, I would like to save "Message **" as an accepted value, but I keep getting an ArgumentException saying: "Nested quantifier *" whenever I try to call Regex.IsMatch on it. Is there any way to workaround this?
public bool ResponseMatch(string responseText)
{
return Regex.IsMatch(responseText, regexPatternString);
}
It sounds like you're trying to match Message ** as a literal value? In this case, call Regex.Escape:
Regex.Escape("Message **") == "Message\ \*\*"
Then you can use it like this:
var valueToMatch = "Message **";
var matches = Regex.IsMatch(input, Regex.Escape(valueToMatch));
However, if you're just using literal values and not any regex features, you might be better off using string.Contains.
"Message *" as a regex means "match any string that has the characters m e s s a g e in that order, then match zero or more spaces".
Regex.IsMatch takes two inputs - the regex to see if it is matched, and the string to run the regex on. Seems you've got the two confused.
If you're trying to legitmately use "Message **" as a regex, you probably mean to escape the "**". If you only need to escape it in handpicked strings, then fix the string to be, say, #"Message \*\*". If you need to fix any number of regex inputs, then run the Regex.Escape over the string first. #"Message \*\*" == Regex.Escape("Message **")
I'm using c# RegEx to search quoted strings in a script text.
I use this expression : new Regex("\"((?:\\\\.|[^\\\\\"]*)*)\""),
e.g "((?:\\.|[^\\\"]*)*)"
meanings to not take care of \" cases
This makes RegEx.Matches runs and never stops for some input strings.
Never mind this problem with .Net RegEx, I know my expression is not the best one.
Before, I used (?<!\\)".*?(?<!\\)" expression but it is not enough for "\\" input string.
The aim is to detect quoted strings before I analyze script codes.
Any one would suggest a good expression ?
It has to work for :
echo("Hello" + yourName + ", here is \"MyTest\"");
path = "\\" + file;
echo("path ends with \\");
(beware, \ are strangely edited with this site)
Thanks a lot.
Usually it is matched using
"((?:[^\\"]|\\.)*)"
See http://www.ideone.com/JiJwa.