简体   繁体   English

分裂为“,”但不是“/”

[英]Splitting on “,” but not “/,”

Question : How do I write an expression to split a string on ',' but not '/,' ? 问题 :如何编写表达式以将字符串拆分为','而不是'/,' Later I'll want to replace '/,' with ', ' . 后来我想用'/,'代替'/,' ', '

Details... 细节...

Delimiter : ',' 分隔符','

Skip Char : '/' 跳过字符'/'

Example input : "Mister,Bill,is,made,of/,clay" 输入示例"Mister,Bill,is,made,of/,clay"

I want to split this input into an array: {"Mister", "Bill", "is", "made", "of, clay"} 我想把这个输入分成一个数组: {"Mister", "Bill", "is", "made", "of, clay"}

I know how to do this with a char prev, cur; 我知道如何使用char prev, cur; and some indexers, but that seems beta. 和一些索引器,但这似乎是beta。

Java Regex has a split functionality, but I don't know how to replicate this behavior in C#. Java Regex具有拆分功能,但我不知道如何在C#中复制此行为。

Note: This isn't a duplicate question, this is the same question but for a different language. 注意:这不是一个重复的问题,这是相同的问题,但对于不同的语言。

I believe you're looking for a negative lookbehind : 我相信你正在寻找负面的背后

var regex = new Regex("(?<!/),");
var result = regex.Split(str);

this will split str on all commas that are not preceded by a slash. 这将在没有斜杠的所有逗号上拆分str If you want to keep the '/,' in the string then this will work for you. 如果你想在字符串中保留'/,'那么这对你有用。

Since you said that you wanted to split the string and later replace the '/,' with ', ' , you'll want to do the above first then you can iterate over the result and replace the strings like so: 既然你说要分割字符串然后', '替换'/,' ,你首先要做上面的事情, 然后你可以迭代结果并替换字符串,如下所示:

var replacedResult = result.Select(s => s.Replace("/,", ", ");
string s = "Mister,Bill,is,made,of/,clay";
var  arr = s.Replace("/,"," ").Split(',');

result : {"Mister", "Bill", "is", "made", "of clay"} 结果: {"Mister", "Bill", "is", "made", "of clay"}

使用正则表达式:

var result = Regex.Split("Mister,Bill,is,made,of/,clay", "(?<=[^/]),");

只需使用“替换”即可删除字符串中的逗号:

 s.Replace("/,", "//").Split(',').Select(x => x.Replace("//", ","));

You can use this in c# 你可以在c#中使用它

string regex = @"(?:[^\/]),";
var match = Regex.Split("Mister,Bill,is,made,of/,clay", regex, RegexOptions.IgnoreCase);

After that you can replace /, and continue your operation as you like 之后,您可以替换/,并继续您的操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM