Suppose there is a text text1(text2)text2
you need to get text1 (text2) text2
Tried to do through the replacement on the regular basis: ([^\s])([\(])|([\)])([^\s])
$1 $2$3 $4
but I get text1 (text2) text3
Suppose there is a text text1(text2)text2
you need to get text1 (text2) text2
Tried to do through the replacement on the regular basis: ([^\s])([\(])|([\)])([^\s])
$1 $2$3 $4
but I get text1 (text2) text3
Let me explain where the extra spaces come from as a result.
Regularity works twice, as there |
.
For the first time, the text before the opening bracket and the bracket itself, respectively, will fall into parameters $ 1 and $ 2. And the parameters $ 3 and $ 4 will remain empty. Therefore, it will output:
text to the bracket, space, opening bracket, empty, space (extra!), empty.
The second time, on the contrary, the first two parameters will remain empty, and the last two will capture the closing bracket and the text after it. Similarly, it will display:
empty, space (extra!), empty, closing bracket, text after the bracket.
I suggest using the Replace
method overload using MatchEvaluator
. In this case, the regular order is the simplest. But I had to use a dictionary with pairs of substitutions.
var dict = new Dictionary<string, string> { ["("] = " (", [")"] = ") " }; string input = "text1(text2)text3"; string pattern = @"\( | \)"; var options = RegexOptions.IgnorePatternWhitespace; string output = Regex.Replace(input, pattern, m => dict[m.Value], options); Console.WriteLine(output);
Comments to other answers suggested that spaces should be added only if they are not present. Probably for this the author used ([^\s])
. In this case, for my version, the regular schedule will be as follows:
@"(?<!\s) \( | \) (?!\s)"
Try not to catch the text to the brackets | after, and the very central part:
Pattern: \s?\((.*)\)\s?
Replacing: " ($1)
" // notice the spaces
You can replace (?=\()|(\))
With $1
.
If you need to make one space, regardless of whether there were spaces, or not, then replace \s*(?:(\()|(\)))\s*
with $2 $1
.
If you do not need to leave spaces between the same brackets, then \s*(?:(\(+)|(\)+))\s*
on $2 $1
.
[^\s]
. - Wiktor Stribiżewtext1ПРОБЕЛ_ПРОБЕЛ(text2) text2
). - Wiktor StribiżewI do not know whether such a replacement will work in C #.
Regular expression to search
(?<=[^\(\s])(?=\()|(?<=\))(?=[^\)\s])
Replacement: space character (!!!)
Test here https://regex101.com/r/cV6oQ7/1
PS A regular does not select anything on its own, but only finds positions between the opening bracket and the symbol in front of it not equal to the whitespace character or opening bracket OR the position between the closing bracket and the symbol behind it is not equal to the closing bracket or white space character.
Source: https://ru.stackoverflow.com/questions/564135/
All Articles