正则表达式和替换字符串的特定字段

问题描述:

我需要对动态生成的字符串进行一些修改;正则表达式和替换字符串的特定字段

String示例

产品[279]电喷涂机[21]喷枪设备[109]喷雾制革设备[23]赠送空气压缩机[33]喷砂枪[5]涂料罐[ 9]空气喷枪[26]气动工具/气动工具[26]轮胎充气枪[10]空气铆钉枪[6]手动工具[7]梳子/毛刷[4]

我想删除“ 产品[279]“从一开始(总是除了数字一样)和重新将字符串的其余部分是这样“电动喷涂机[21] -喷枪设备[109] - ...”

+0

你真的需要Regex来完成这么简单的任务吗?你有尝试过吗?'str = str.Substring(str.IndexOf(']')+ 2)' – 2012-01-06 22:14:47

Demo

String sample = @"Products [279] Electric Paint Sprayer [21] Airbrush Equipment [109] Spray Tanning Equipment [23] Mini Air Compressor [33] Sand blasting gun [5] Paint Tank [9] Air Spray Gun [26] Pneumatic tools/Air tools [26] Tire Inflating gun [10] Air Riveter [6] Hand Tools [7] Comb/Hair Brush [4]"; 

// Remove "Products [#] " 
sample = Regex.Replace(sample, @"^Products \[\d+\]\s*", String.Empty); 

// Add hyphens 
sample = Regex.Replace(sample, @"(\[\d+\])(?=\s*\w)", @"$1 - "); 
// the (?=\s*\w) makes sure we only add a hyphen when there's more information 
// ahead (and not a hyphen to the end of the string) 

结果:

电动喷漆器[21] - 喷笔设备[109] - 喷雾制革设备[23] - 迷你空气压缩机[33] - 喷砂枪[5] - 油漆罐[9] - 空气喷枪[26] - 气动工具/气动工具[26] - 轮胎充气枪[10] - 气铆枪[6] - 手工工具[7] - 梳子/毛刷[4]

+0

就像一个魅力。谢谢。 – 2012-01-06 22:20:49

您可以使用String.Remove或与string.replace做到这一点。请记住,这不会修改该字符串,但会返回一个新字符串。噢,为了找到产品[XXX],你可以使用String.SubString(0,String.IndexOf(']'));查找包含']'的第一个实例的字符串。

步骤如下:

  • 取代^\w+\s+\[\d+\]\s+什么也没有(在你的榜样删除Products [279]<space>);
  • 全球取代(?<\])(?=\s+.)<space>-
+0

谢谢#fge,第一个工作,但第二个给我错误。 – 2012-01-06 22:20:19