Regex для замены символа и в кавычках C # - PullRequest
0 голосов
/ 30 июня 2019

Я пытаюсь заменить '&' внутри кавычек.

Вход

"I & my friends are stuck here", & we can't resolve

Выход

"I and my friends are stuck here", & we can't resolve

Заменить '&' на 'и' и только внутри кавычек, не могли бы вы помочь?

Ответы [ 2 ]

1 голос
/ 30 июня 2019

Безусловно, самый быстрый способ - использовать конструкцию \G и делать это с одним регулярным выражением.

C # код

var str =
    "\"I & my friends are stuck here & we can't get up\", & we can't resolve\n" +
    "=> \"I and my friends are stuck here and we can't get up\", & we can't resolve\n";
var rx = @"((?:""(?=[^""]*"")|(?<!""|^)\G)[^""&]*)(?:(&)|(""))";
var res = Regex.Replace(str, rx, m =>
        // Replace the ampersands  inside double quotes with 'and'
        m.Groups[1].Value + (m.Groups[2].Value.Length > 0 ? "and" : m.Groups[3].Value));
Console.WriteLine(res);

Выход

"I and my friends are stuck here and we can't get up", & we can't resolve
=> "I and my friends are stuck here and we can't get up", & we can't resolve

Regex ((?:"(?=[^"]*")|(?<!"|^)\G)[^"&]*)(?:(&)|("))

https://regex101.com/r/db8VkQ/1

Объяснено

 (                          # (1 start), Preamble

      (?:                        # Block
           "                          # Begin of quote
           (?= [^"]* " )              # One-time check for close quote
        |                           # or,
           (?<! " | ^ )               # If not a quote behind or BOS
           \G                         # Start match where last left off
      )
      [^"&]*                     # Many non-quote, non-ampersand
 )                          # (1 end)

 (?:                        # Body
      ( & )                      # (2), Ampersand, replace with 'and'
   |                           # or,
      ( " )                      # (3), End of quote, just put back "
 )

Тест

Regex1:   ((?:"(?=[^"]*")|(?<!"|^)\G)[^"&]*)(?:(&)|("))
Completed iterations:   50  /  50     ( x 1000 )
Matches found per iteration:   10
Elapsed Time:    2.21 s,   2209.03 ms,   2209035 µs
Matches per sec:   226,343
0 голосов
/ 01 июля 2019

Используйте

Regex.Replace(s, "\"[^\"]*\"", m => Regex.Replace(m.Value, @"\B&\B", "and"))

См. Демоверсию C # :

using System;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var s = "\"I & my friends are stuck here\", & we can't resolve";
        Console.WriteLine(
            Regex.Replace(s, "\"[^\"]*\"", m => Regex.Replace(m.Value, @"\B&\B", "and"))
        );
    }
}

Выход: "I and my friends are stuck here", & we can't resolve

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...