求一个正则表达式的写法
请问这样的规则是否可以用正则来处理?
100 @a20041121d2004 em y0chiy50 ea
1010 @achi
71102 @a法律出版社@b法规中心@4编@9fa lv chu ban she
上面字符串在\r\n后面如果第五个字符是@,那就在@前加一个空格,也就是
100 @a20041121d2004 em y0chiy50 ea 要变成
100 @a20041121d2004 em y0chiy50 ea
在\r\n后面如果第七个字符是@,那就把@前面的空格去掉
71102 @a法律出版社@b法规中心@4编@9fa lv chu ban she 要改成
71102@a法律出版社@b法规中心@4编@9fa lv chu ban she
像1010 @achi 这样的不需要变
不知道用正则来处理行不行?
------解决方案--------------------private void button4_Click(object sender, EventArgs e)
{
string strSrc = "71102 @a法律出版社@b法规中心@4编@9fa lv chu ban she\r\n100 @a20041121d2004 em y0chiy50 ea ";
string strDst = Regex.Replace(strSrc, "([^@]{4})(@.*)|([^@]{5}) (@.*) ", Matcher);
MessageBox.Show(strDst);
}
public string Matcher(Match m)
{
if (m.Groups[1].Value != string.Empty)
{
return m.Groups[1].Value + " " + m.Groups[2].Value;
}
else
{
return m.Groups[3].Value + m.Groups[4].Value;
}
}
------解决方案--------------------string yourStr = ..............;
string result = Regex.Replace(yourStr, @ "^(.{4}|.{6})(?=@) ", new MatchEvaluator(regReplace), RegexOptions.Multiline);
private string regReplace(Match m)
{
if (m.Value.Length == 4)
return m.Value + " ";
if (m.Value.Length == 6)
return m.Value.Remove(5, 1);
return m.Value;
}
另外,是否需要判断@前一字符是否为空格,以上未做判断,需做判断的这行改下
string result = Regex.Replace(yourStr, @ "^(.{3}|.{5}) (?=@) ", new MatchEvaluator(regReplace), RegexOptions.Multiline);
------解决方案--------------------string s1=@ "(? <=\r\n)[\s\S]{4}\@ ";
string s2=@ "(? <=\r\n)[\s\S]{6}\@ ";
string s= "100 @a20041121d2004 em y0chiy50 ea\r\n1010 @achi\r\n71102 @a法律出版社@b法规中心@4编@9fa lv chu ban she ";
string s3;
Regex re=new Regex(s1);
foreach(Match m in re.Matches(s);
{
s3=m.Group[0].value;
s.Replace(s3,s3.Replace( " ", " ");
}
Regex re=new Regex(s2);
foreach(Match m in re.Matches(s);
{
s3=m.Group[0].value;
s.Replace(s3,s3.Replace( " ", " ");
}