以几种组合替换

String Replace in several combinations

本文关键字:几种 组合 替换      更新时间:2023-10-16

我有一个XY坐标的文件,我想用数字"0"替换"空"坐标。

文件:

X123Y456
XY123
X123
Y123 
X123Y
XY123
X
Y

样式:

Xn -> X0
Yn -> Y0
XY  -> X0Y

实际上我认为正则表达式会很好使用,但我不确定如何做到这一点。所以我使用简单的字符串::替换到目前为止。对我来说,复杂的事情是不仅情况可能发生,而且每行也不是只有一个。

我想我应该可以这样做:

System::Text::RegularExpressions::Regex::Replace(INPUT, PATTERN, REPLACE);

输入对我来说很清楚,模式不完全是由于不同的组:

(^X$) -> X0
(Y$)  -> Y0
(^XY) -> X0Y
(^XY$) -> X0Y0

会得到类似。

(^X$)|(Y$)|(^XY)

替换将会像这样:

$0 -> X0
$1 -> Y0
$2 -> X0Y

到目前为止我所做的是简单的String::Replace:

  void searchReplace(String^ sFile)
  {
    if(!System::IO::File::Exists(sFile))
      return;
    System::IO::StreamReader^ sr = gcnew System::IO::StreamReader(sFile);
    System::IO::StreamWriter^ sw = gcnew System::IO::StreamWriter(sFile + ".tmp");
    String^ newLine = System::Environment::NewLine;
    //System::Text::RegularExpressions::Regex regex = System::Text::RegularExpressions::Regex();
    String^ pattern = "(X"+newLine+")";
    String^ sLine = "";
    while((sLine = sr->ReadLine()) != nullptr)
    {
      String^ sRes = sLine->Trim()->Replace("Y"+newLine, "Y0");
      sRes = sRes->Replace("XY", "X0Y");
      sRes = sRes->Replace("X"+newLine, "X0"); 
      sw->WriteLine(sRes);
    }
    sr->Close();
    sw->Close();
    // TODO copy / delete
  }
由于其他问题,

还没有尝试这个,但它基本上应该工作。但是它对我来说似乎不是那么完美,regex应该更好使用。

是否有任何方法可以用正则表达式或字符串取代最佳方式?如果是这样,我应该如何使用Regex::替换正确?

任何帮助/提示/建议都将是非常好的。


编辑解决方案:

谢谢你的帮助。以下是对我来说运行良好的最终版本:

  void searchReplace(String^ sFile)
  {
    if(!System::IO::File::Exists(sFile))
      return;
    System::IO::StreamReader^ sr = gcnew System::IO::StreamReader(sFile);
    System::IO::StreamWriter^ sw = gcnew System::IO::StreamWriter(sFile + ".tmp");
    String^ sLine = "";
    while((sLine = sr->ReadLine()) != nullptr)
    {
      sw->WriteLine(Regex::Replace(sLine->Trim(), "(?<=[XY])(?=D|$)(?!-)", "0"));
    }
    sr->Close();
    sw->Close();
    // TODO copy / delete
  }
输入:

X-123Y-456
XY-123
X123
Y123 
X123Y
XY123
X
Y
输出:

X-123Y-456
X0Y-123
X123
Y123
X123Y0
X0Y123
X0
Y0

编辑2:增加了负坐标的模式,我没有在我的描述中提到。

(?<=[XY])(?=D|$)(?!-)

您可以使用以下正则表达式:

String output = Regex.Replace(input, @"(?<=[XY])(?=D|$)", "0");

:

(?<=       # look behind to see if there is:
  [XY]     #   any character of: 'X', 'Y'
)          # end of look-behind
(?=        # look ahead to see if there is:
  D       #   non-digits (all but 0-9)
 |         #  OR
  $        #   before an optional n, and the end of the string
)          # end of look-ahead

(现场演示 | 工作演示)

(X|Y)(?!d)

匹配后面没有数字的"X"或"Y"的所有实例,并捕获第一个捕获组中的哪一个(X或Y)。

你可以这样写

output = System::Text::RegularExpressions::Regex.Replace(input, "(X|Y)(?!\d)", "$10");

注意这个表达式将"XY"替换为"X0Y",而不是"X0Y"。这可以接受吗?