Regexp Scroll Template

Problem

I need to replace all asterisk characters ('*') with a percent character ('%'). Asterisks in square brackets should be ignored.

Example

    [Test]
    public void Replace_all_asterisks_outside_the_square_brackets()
    {
        var input = "Hel[*o], w*rld!";
        var output = Regex.Replace(input, "What_pattern_should_be_there?", "%")

        Assert.AreEqual("Hel[*o], w%rld!", output));
    }
+5
source share
3 answers

Try using the look:

\*(?![^\[\]]*\])

Here's a slightly stronger solution that takes care of [], better blocks and even avoids characters \[:

string text = @"h*H\[el[*o], w*rl\]d!";
string pattern = @"
\\.                 # Match an escaped character. (to skip over it)
|
\[                  # Match a character class 
    (?:\\.|[^\]])*  # which may also contain escaped characters (to skip over it)
\]
|
(?<Asterisk>\*)     # Match `*` and add it to a group.
";

text = Regex.Replace(text, pattern,
    match => match.Groups["Asterisk"].Success ? "%" : match.Value,
    RegexOptions.IgnorePatternWhitespace);

If you don't need escaped characters, you can simplify it:

\[          # Skip a character class
    [^\]]*  # until the first ']'
\]
|
(?<Asterisk>\*)

That can be written without comment as @"\[[^\]]*\]|(?<Asterisk>\*)".

, , , Regex.Replace: . , . , .
[...], , , . , Asterisk .

+3

RegEx. . , :

[Test]
public void Replace_all_asterisks_outside_the_square_brackets()
{
    var input = "H*]e*l[*o], w*rl[*d*o] [o*] [o*o].";
    var actual = ReplaceAsterisksNotInSquareBrackets(input);
    var expected = "H%]e%l[*o], w%rl[*d*o] [o*] [o*o].";

    Assert.AreEqual(expected, actual);
}

private static string ReplaceAsterisksNotInSquareBrackets(string s)
{
    Regex rx = new Regex(@"(?<=\[[^\[\]]*)(?<asterisk>\*)(?=[^\[\]]*\])");

    var matches = rx.Matches(s);
    s = s.Replace('*', '%');

    foreach (Match match in matches)
    {
        s = s.Remove(match.Groups["asterisk"].Index, 1);
        s = s.Insert(match.Groups["asterisk"].Index, "*");
    }
    return s;
}
+2

EDITED

, ;)

lookbehind (?<!) (?!).

var output = Regex.Replace(input, @"(?<!\[)\*(?!\])", "%");

It also passes the test in the comment to another answer "Hel*o], w*rld!"

-1
source

All Articles