I want to replace hyphen character with space if it is NOT enclosed by digits on both sides.
string str = "Hefer 789-567 dfg-5mh";
str = Regex.Replace(str, #"[a-zA-Z]\-(\d+)", "$1");
Output
Hefer 789-567 df5mh
Desired output
Hefer 789-567 dfg 5mh
You can use negative lookahead and lookbehind: (?<!\d)-|-(?!\d) says "match a - that is not preceeded by a \d or a - that is not followed by a \d".
Thus your regex would be something like
string str = "Hefer 789-567 dfg-5gh";
str = Regex.Replace(str, #"(?<!\d)-|-(?!\d)", " ");
Edit: Note that this also replaces hyphens at the start or end of the string. If you want to avoid this you can use (?<!\d|^)-(?=.)|(?<=.)-(?!\d|$) or (?<=[^\d])-(?=.)|(?<=.)-(?=[^\d]).
The problem you are describing in your title can be solved using this:
Regex.Replace(str, #"(?<=[A-Za-z])-", " ");
The problem you are describing in the body of your question can be solved using this:
Regex.Replace(str, #"(?<!\d)-|-(?!\d)", " ");
Or without lookaround:
Regex.Replace(str, #"([^\d])-|-([^\d])", "$1 $2");
Related
I am looking everywhere but can't find the answer. I need a regex which removes all spaces in a string but keeps only the ones that are inside "".
Example: $F:2 $PX:30 $PY:980 $T: " " or $F:A $PX:30B $PY:9K80 $T: " " so in the end it should look like $F:2$PX:30$PY:980$T:" "
It would be valuable to explain how to read the regex that you answer.
This will match whitespace which is touching a ", yet not enclosed by them.
" +(?!\")|(?<!\") +"
And for all white space:
"\s+(?!\")|(?<!\")\s+"
You can test it on Regex101 or Rextester
The Greatest Regex Trick Ever is quite helpful in such cases:
var str = "$F:2 $PX:30 $PY:980 \" \"$T:\" \"";
str = Regex.Replace(str, "\"\\s+\"|\\s+", m => { return m.Value.StartsWith("\"") ? m.Value : ""; });
Console.WriteLine(str);
Demo: https://dotnetfiddle.net/Q54FlJ
Matching a space not preceeded nor followed by quotation mark:
(?<!") (?!")
Matching all whitespace:
(?<!")\s+(?!")
Note: This might not work on more than one space, as pointed out by Dmitry.
I have the following input string:
string val = "[01/02/70]\nhello world ";
I want to get the all words after the last ] character.
Example output for a sample string above:
\nhello world
In C#, use Substring() with IndexOf:
string val = val.Substring(val.IndexOf(']') + 1);
If you have multiple ] symbols, and you want to get all the string after the last one, use LastIndexOf:
string val = "[01/02/70]\nhello [01/02/80] world ";
string val = val.Substring(val.LastIndexOf(']') + 1); // => " world "
If you are a fan of Regex, you might want to use a Regex.Replace like
string val = "[01/02/70]\nhello [01/02/80] world ";
val = Regex.Replace(val, #"^.*\]", string.Empty, RegexOptions.Singleline); // => " world "
See demo
Notes on REGEX:
RegexOptions.Singleline makes . match a linebreak
^ - matches beginning of string
.* - matches 0 or more characters but as many as possible (greedy matching)
\] - matches literal ] (as it is a special regex metacharacter, it must be escaped).
You need to use lookbehind assertion. And not only that, you have to enable DOTALL modifier also, so that it would also match the newline character present inbetween.
"(?s)(?<=\\]).*"
(?s) - DOTALL modifier.
(?<=\\]) - lookbehind which asserts that the match must be preceeded by a close bracket
.* - Matches any chracater zero or more times.
or
"(?s)(?<=\\])[\\s\\S]*"
Try this if you don't want to match the following newline character.
#"(?<=\][\n\r]*).*"
I have two strings :-
String S1 = "This is my\r\n string."
String S2 = "This is my\n self."
I want to have a generic method to replace any existence of "\n" to "\r\n". But it should not replace any part of the string if it already has "\r\n".
Use regular expression with negative lookbehind:
string result = Regex.Replace(input, #"(?<!\r)\n", "\r\n");
It matches all \n which are not preceded by \r.
Try something like this:
var unused = "ยง";
S2 =
S2
.Replace("\r\n", unused)
.Replace("\n", unused)
.Replace(unused, "\r\n");
Assuming you have well-behaved standard input text, i.e. no consecutive \r, you can simply use:
var result = S1.replace("\n","\r\n").replace("\r\r","\r")
This won't work in general cases, obviously
I have a regex
[A-Za-z]
and a string, such as
Hi! This is a string.
I want to replace all charcters that are not in the Regex with space. So, I'll end up with
Hi This is a string
How is this done?
var cleaned = Regex.Replace(given, "[^A-Za-z]", " ");
Try:
string output = Regex.Replace(input, "[^A-Za-z]", " ");
I have a string that will have multiple whitespace characters in it and I'm wanting to seperate each word by 1 whitespace character. Say if the string is "Hi! My name is troy and i love waffles!", I want to trim that so it is "Hi! My name is troy and I love waffles!". How would I do this?
Use the regular expression \s+ (one or more whitespace) with the Regex.Replace method from the System.Text.RegularExpressions namespace:
s = Regex.Replace(s, #"\s+", " ");
If you just want to replace spaces you can change the "\s" to a space "":
s = Regex.Replace(s, #" +", " ");
string.Join(" ","Hi! My name is troy and i love waffles!"
.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries)
.Select (s => s.Trim()))
Try this:
var input = "Hi! My name is troy and i love waffles!";
var output = Regex.Replace(input, #"\s{2,}", string.Empty);
Console.WriteLine(output); //Hi! My name is troy and I love waffles!