2

我想从字符串中删除 [number];

输入示例是:

1 - 家庭住址 [我的第一个家庭住址 #12] [1350]
2 - 这里有一些文字(这里有一些文字)一些
3 - 你好 dolor sit amet [kost street #74] [1008]

输出示例是:

1 - 家庭住址 [我的第一个家庭住址 #12]
2 - 这里有一些文字(这里有一些文字)一些
3 - 你好 dolor sit amet [kost street #74]

我试过的

var pattern = @"^[\d+]$";
var result = Regex.Replace(value, pattern, "");

我想删除带有二次符号“ [ ”和“ ] ”的粗体文本,如果它根本不包含它,则保持原样(参见第二个示例)。

4

3 回答 3

3

The pattern you tried "^[\d+]$ was almost correct! The problem with that pattern is that you are using the anchors ^...$ which basically denote that the pattern will only match the digits encapsulated in braces if they are the ONLY string of characters in the input. See the MSDN documentation on Anchors for a more technical summary.

The pattern \[\d+\] will match any digits encapsulated in square braces.

Using Regex.Replace :-

input = Regex.Replace(input, @"\[\d+\]", string.Empty);
于 2013-06-29T13:27:22.150 回答
1

Try the following:

input = "home address [my first home address #12] [1350]"
string pattern = @"\[\d+\]";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

Update: (After the question was updated with some code...)

var pattern = @"^[\d+]$";

This pattern will only work against numbers. The following pattern should work for you:

var pattern = @"\[\d+\]";
于 2013-06-29T13:24:38.420 回答
0

对于您的示例,您不需要正则表达式。

string address = "home address [my first home address #12] [1350]";

if(address.Count(x => x == '[') >= 2))
   address = address.Substring(0, address.LastIndexOf('['));
于 2013-06-29T14:03:43.630 回答