Well I was able to figure this out after a couple of days at it.
This issue here is that Regex is that it will match a string as a whole, so if I wanted the exclude a character from a match I could do so by using Regex to drop either the first or last character in the matched string. But unfortunately, you can’t not capture a character inside the matched result.
So when I want to match a character either side of another one like below;
So from my understanding of RegEx it is impossible.
However, I was able to use look-around
to match each character either side, but b/c it was not a single match, it had the undesired result of matching just single characters as well, such as below;
Code is,
var match = Regex.IsMatch(text, @"(?<=[a-zA-Z0-9])[=@\-_]|[=@\-_](?=[a-zA-Z0-9])");
And the results were this below, which also matched just single characters which was not desired.
So a change of thinking to the approach (which I don’t know why I did not do in the first place, apart from the fact that I was so focused on matching the character either side of the desired character, I could not see the forest for the trees). The approach was to match when two of the same characters came before Word Characters
or Digits
, so I used look-around
again and came up with this;
Here is the code,
var match = Regex.IsMatch(subjectString, @"[=@\-_]{2}(?=[a-zA-Z0-9])");
Whit the result looking like this,
Which now was what I was looking for. But, that did not solve the issue as when the character or string in the middle was different to the characters either side, to which the above would fail.
So I came up with this, and the answer to my question in my case. It is not a complete match , but matches two different conditions to get the result I needed.
var match = Regex.IsMatch(subjectString, @"(?<=[a-zA-Z0-9])[@\-=_](?=[@\-=_])|(?<=[@\-=_])[@\-=_](?=[a-zA-Z0-9])");
And the results are this;
I don’t really care what people thought of the question, but hopefully this answer will help someone tries to do a single match on a character
either side of a string
or character
solved Replace Chars inside either side of string?