以几种组合替换
String Replace in several combinations
我有一个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"。这可以接受吗?
相关文章:
- 在C++中,如何通过几种类型从元组中选择多个元素
- 如何在同一个模板功能上专门化几种类型?
- 在 C 中并行化嵌套循环的几种方法之间的差异,C++使用 OpenMP
- Qt - 在没有正则表达式的情况下,将 QString 拆分为几种类型的空格
- 从文件中读取未签名字符的几种不同方法
- C++阿特金的筛子返回了几种复合材料
- 最简单的方法来封装几个语句中的几种语句
- 一些应用程序是如何用几种编程语言制作的
- 在 C++Amp 中并行执行的几种算术运算
- 链表的几种实现 - C++
- 几种特定方法或一种通用方法
- Qt-拆分一个QString,使用几种类型的空白作为分隔符
- 将 void* 强制转换为仅在运行时已知的几种类型
- C ++中的几种分配内存方法有什么区别
- LNK2019错误-未找到外部符号.尝试了几种解决方案
- 声明空/默认构造函数的几种方法之间的差异
- 以几种组合替换
- 将几种类型的数据读入数组
- 用指针写条件的几种方式的区别
- 检查几个组合框的索引是否唯一