I have this partial search regex, that is 3 regex's with a or '|'
return new Regex(@"(?<=\S)"+aFrom+@"(?=\S)|(?<=\S)"+aFrom+@"(?=\u000D|\s|$)|(?<=\u000D|\s|^)"+aFrom+@"(?=\S)", aCaseSensitivity);
Where aFrom
is a string and aCaseSensitivity
is from RegexOptions Enum.
I'm wondering if anyone knows if there's a good way to compact these regex's into one regex without it losing it's purpose?
I've tried different AI tools, but they change the regex to the point it's useless for my purpose. I've used the regex101 site for debugging, but I can't come up with any good solution.
For clarity: I want the regex to match if "aFrom" in any way connected to another string or encapsulated by it.
I have this partial search regex, that is 3 regex's with a or '|'
return new Regex(@"(?<=\S)"+aFrom+@"(?=\S)|(?<=\S)"+aFrom+@"(?=\u000D|\s|$)|(?<=\u000D|\s|^)"+aFrom+@"(?=\S)", aCaseSensitivity);
Where aFrom
is a string and aCaseSensitivity
is from RegexOptions Enum.
I'm wondering if anyone knows if there's a good way to compact these regex's into one regex without it losing it's purpose?
I've tried different AI tools, but they change the regex to the point it's useless for my purpose. I've used the regex101 site for debugging, but I can't come up with any good solution.
For clarity: I want the regex to match if "aFrom" in any way connected to another string or encapsulated by it.
Share Improve this question edited Feb 6 at 11:56 DanTheMan asked Feb 6 at 11:33 DanTheManDanTheMan 275 bronze badges New contributor DanTheMan is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 3 |2 Answers
Reset to default 4I want the regex to match if "aFrom" in any way connected to another string or encapsulated by it.
So $@"(?<=\S){aFrom}|{aFrom}(?=\S)"
should work for you: it checks if aFrom is preceded and/or followed by a non space character
I could only suggest splitting entire regex into separate parts:
string part1 = $@"(?<=\S){aFrom}(?=\S)";
string part2 = $@"(?<=\S){aFrom}(?=\u000D|\s|$)";
string part3 = $@"(?<=\u000D|\s|^){aFrom}(?=\S)";
Regex regex = new Regex($"{part1}|{part2}|{part3}", aCaseSensitivity);
"^\s*" + aFrom + "\s*$"
seeing as you don't seem to care what whitespace is before and after? Your three options are 1. no space before & after 2. no space before, any WS or end of string 3. WS or begin string, no whitespace after. How about you state exactly what conditions you are trying to enforce. – Charlieface Commented Feb 6 at 11:42