Given $displayHeight = "800";, replace whatever number is at 800 with int value y_res.
resultString = Regex.Replace(
im_cfg_contents,
#"\$displayHeight[\s]*=[\s]*""(.*)"";",
Convert.ToString(y_res));
In Python I'd use re.sub and it would work. In .NET it replaces the whole line, not the matched group.
What is a quick fix?
Building on a couple of the answers already posted. The Zero-width assertion allows you to do a regular expression match without placing those characters in the match. By placing the first part of the string in a group we've separated it from the digits that you want to be replaced. Then by using a zero-width lookbehind assertion in that group we allow the regular expression to proceed as normal but omit the characters in that group in the match. Similarly, we've placed the last part of the string in a group, and used a zero-width lookahead assertion. Grouping Constructs on MSDN shows the groups as well as the assertions.
resultString = Regex.Replace(
im_cfg_contents,
#"(?<=\$displayHeight[\s]*=[\s]*"")(.*)(?="";)",
Convert.ToString(y_res));
Another approach would be to use the following code. The modification to the regular expression is just placing the first part in a group and the last part in a group. Then in the replace string, we add back in the first and third groups. Not quite as nice as the first approach, but not quite as bad as writing out the $displayHeight part. Substitutions on MSDN shows how the $ characters work.
resultString = Regex.Replace(
im_cfg_contents,
#"(\$displayHeight[\s]*=[\s]*"")(.*)("";)",
"${1}" + Convert.ToString(y_res) + "${3}");
Try this:
resultString = Regex.Replace(
im_cfg_contents,
#"\$displayHeight[\s]*=[\s]*""(.*)"";",
#"\$displayHeight = """ + Convert.ToString(y_res) + #""";");
It replaces the whole string because you've matched the whole string - nothing about this statement tells C# to replace just the matched group, it will find and store that matched group sure, but it's still matching the whole string overall.
You can either change your replacer to:
#"\$displayHeight = """ + Convert.ToString(y_res) + #""";"
..or you can change your pattern to just match the digits, i.e.:
#"[0-9]+"
..or you could see if C# regex supports lookarounds (I'm not sure if it does offhand) and change your match accordingly.
You could also try this, though I think it is a little slower than my other method:
resultString = Regex.Replace(
im_cfg_contents,
"(?<=\\$displayHeight[\\s]*=[\\s]*\").*(?=\";)",
Convert.ToString(y_res));
Check this pattern out
(?<=(\$displayHeight\s*=\s*"))\d+(?=";)
A word about "lookaround".
Related
I'm quite the Regex novice, but I have a series of strings similar to this "[$myVar.myVar_STATE]" I need to replace the 2nd myVar that begins with a period and ends with an underscore. I need it to match it exactly, as sometimes I'll have "[$myVar.myVar_moreMyVar_STATE]" and in that case I wouldn't want to replace anything.
I've tried things like "\b.myVar_\b", "\.\bmyVar_\b" and several more, all to no luck.
How about this:
\[\$myVar\.([^_]+)_STATE\]
Matches:
[$myVar.myVar_STATE] // matches and captures 'myvar'
[$myVar.myVar_moreMyVar_STATE] // no match
Working regex example:
http://regex101.com/r/yM9jQ3
Or if _STATE was variable, you could use this: (as long as the text in the STATE part does not have underscores in it.)
\[\$myVar\.([^_]+)_[^_]+\]
Working regex example:
http://regex101.com/r/kW8oE1
Edit: Conforming to OP's comments below, This should be what he's going for:
(\[\$myVar\.)([^_]+)(_[^_]+\])
Regex replace example:
http://regex101.com/r/pU6yL8
C#
var pattern = #"(\[\$myVar\.)([^_]+)(_[^_]+\])";
var replaced = Regex.Replace(input, pattern, "$1"+ newVar + "$3")
What about something like:
.*.(myVar_).*
This looks for anything then a . and "myVar_" followed by anything.
It matches:
"[$myVar.myVar_STATE]"
And only the first myVar_ here:
"[$myVar.myVar_moremyVar_STATE]"
See it in action.
This should do it:
\[\$myVar\.(.*?)_STATE\]
You can use this little trick to pick out the groups, and build the replacement at the end, like so:
var replacement = "something";
var input = #"[$myVar.myVar_STATE]";
var pattern = #"(\[\$myVar\.)(.*?)_(.*?)]";
var replaced = Regex.Replace(input, pattern, "$1"+ replacement + "_$2]")
C# already has builtin method to do this
string text = ".asda_";
Response.Write((text.StartsWith(".") && text.EndsWith("_")));
Is Regex really required?
string input = "[$myVar.myVar_STATE]";
string oldVar = "myVar";
string newVar = "myNewVar";
string result = input.Replace("." + oldVar + "_STATE]", "." + newVar + "_STATE]");
In case "STATE" is a variable part, then we'll need to use Regex. The easiest way is to use this Regex pattern which matches a position between a prefix and a suffix. Prefix and suffix are used for searching but are not included in the resulting match:
(?<=prefix)find(?=suffix)
result =
Regex.Replace(input, #"(?<=\.)" + Regex.Escape(oldVar) + "(?=_[A-Z]+])", newVar);
Explanation:
The prefix part is \., which stand for ".".
The find part is the escaped old variable to be replaced. Regex escaping makes sure that characters with a special meaning in Regex are escaped.
The suffix part is _[A-Z]+], an underscore followed by at least one letter followed by "]". Note: the second ] needs not to be escaped. An opening bracket [ would have to be escaped like this: \[. We cannot use \w for word characters for the STATE-part as \w includes underscores. You might have to adapt the [A-Z] part to exactly match all possible states (e.g. if state has digits, use [A-Z0-9].
Well the title says it all ...
I have a file containing different flavors of the same string followed by different integers. Let's say I have ABC42 a couple of times, a few ABC422 and one ABC4244.
I want to replace "ABC42" by "Douglas" and keep the ABS422 and ABC4244 intact in the text.
I'm using the .Net Regular Expression parser.
Thanks in advance
You can use word boundaries (the \b metacharacter) to match the intended text exactly. Your pattern would be: \bABC42\b
string input = " Let's say I have ABC42 a couple of times, a few ABC422 and one ABC4244.";
string pattern = #"\bABC42\b";
string result = Regex.Replace(input, pattern, "Douglas");
EDIT: in response to the comment asking whether this would work for "zzABC42_"...
It won't work in that case since the entire point of using \b is to match a word boundary. Since the pattern surrounds "ABC42" with \b, it matches the whole word. To match "zzABC42_" we can't use word boundaries anymore.
Instead, we need to partially match it and come up with a new criteria. Let's assume this criteria is partially match "ABC42" as long as no other digits follow "42". I can drop the \b and use a negative look-ahead to prevent extra digits from being matched. This would resemble the following pattern: ABC42(?!\d)
string input = "Hello zzABC42_, ABC422 and ABC4244.";
string pattern = #"ABC42(?!\d)";
string result = Regex.Replace(input, pattern, "Douglas");
You can use the following code provided that ABC42 is a word on its own (regex below matches based on word boundaries).
String input = "ABC42 a couple of times, a few ABC422 and one ABC4244 ABC42.";
String pattern = #"\bABC42\b";
String output = Regex.Replace(input, pattern, "Douglas");
Say you have a string:
string s = "GameObject.Find(\"obj\").GetComponent(\"comp\").GetMethod(\"method\").Get...";
The string can have any number of GetX() methods appended to it.
And you need to separate each method without the "." separator. Although, GameObject.Find can keep the (dot).
Here is my code so far :
Match match = Regex.Match(s, "(.+?\\(\".+?\"\\))(?:\\.??)*");
This produces only one group. What is the correct solution to this problem?
Edit :
Updated with non-capturing group.
First I'd recommend using verbatim string literals for writing regular expressions in C#. This cuts down the number of backslashes you need to write.
#"(.+?\("".+?""\)\.??)*"
To get all the captures, inspect Match.Captures.
See it working online: ideone
Is there any regular expression that will replace everything except alphanumeric?
My attempt (not working)
string str = "This is a string;;;; having;;; and It also 5555 777has dot (.) Many dots(.....)";
Regex rgx2 = new Regex("^[a-zA-Z0-9]+");
string result1 = rgx2.Replace(str, "");
[^a-zA-Z0-9]+ instead ^[a-zA-Z0-9]+
The ^ symbol in your second regex means 'at start of string', the way it is written. In order to have it negate the set it needs to be the first character after opening bracket:
[^a-zA-Z0-9]+
However, this will remove the - characters that you previously replaced spaces with. You probably want to exclude that character as well:
[^a-zA-Z0-9-]+
What would be the regex expression to find (PoundSomenumberSemiColonPound) (aka #Number;#)? I used this but not working
string st = Regex.Replace(string1, #"(#([\d]);#)", string.Empty);
You're looking for #\d+;#.
\d matches a single numeric character
+ matches one or more of the preceding character.
(\x23\d+\x3B\x32)
# and / are both used around patterns, thus the trouble. Try using the above (usually when I come in to trouble with specific characters I revert to their hex facsimile (asciitable.com has a good reference)
EDIT Forgot to group for replacement.
EDITv2 The below worked for me:
String string1 = "sdlfkjsld#132;#sdfsdfsdf#1;#sdfsdfsf#34d;#sdfs";
String string2 = System.Text.RegularExpressions.Regex.Replace(string1, #"(\x23\d+\x3B\x23)", String.Empty);
Console.WriteLine("from: {0}\r\n to: {1}", string1, string2);;
Output:
from: sdlfkjsld#132;#sdfsdfsdf#1;#sdfsdfsf#34d;#sdfs
to: sdlfkjsldsdfsdfsdfsdfsdfsf#34d;#sdfs
Press any key to continue . . .
You don't need a character class when using \d, and as SLaks points out you need + to match one or more digits. Also, since you're not capturing anything the parentheses are redundant too, so something like this should do it
string st = Regex.Replace(string1, #"#\d+;#", string.Empty);
You may need to escape the # symbols, they're usually interpreted as comment markers, in addition to #SLaks comment about using + to allow multiple digits