0

我有一个如下字符串:

string strAttachment = "3469$cosmeticsview@.png,3470SQL.txt";  

我要这个:

cosmeticsview.png,SQL.txt

我试试这个:

var result = Regex.Replace(strAttachment, @"\d+@+$", "");
Response.Write(result);

但不工作。

我认为导致这个问题的原因是 $ 符号。

编辑

我也想删除数字

4

3 回答 3

1

您在这里有两个问题-首先是转义特殊的正则表达式符号(在您的情况下为行尾)。第二个是错误的模式 - 您当前的解决方案试图@在数字之后匹配:

   one or more @ character
       |
       | end of line
       | |
    \d+@+$
     |
one or more digit

hello1234@当然,这不是你的情况。您想删除带有美元符号的数字或 @ 字符。这是正确的模式:

  one optional $ character
        |
        | OR
        | |
    \d+\$?|@
     |     |
     |   @ character
     |
one or more digit

这是代码:

string strAttachment = "3469$cosmeticsview@.png,3470SQL.txt";  
var result = Regex.Replace(strAttachment, @"\d+\$?|@", "");

或者,如果您只想从字符串中删除任何数字、美元和 @:

var result = Regex.Replace(strAttachment, @"[\d\$@]+", "");
于 2013-10-29T12:12:09.530 回答
1

尝试逃避它\$

它在正则表达式中保留以指示行尾

此外,@+不需要 - 这不是正则表达式的工作方式。要获得您想要的结果:

\d+\$

然后使用替换@

var result = Regex.Replace(strAttachment, @"\d+$", "").Replace("@","");
于 2013-10-29T12:06:42.047 回答
0

I think you're complicating this by trying to make a single pass. First get the part of the string you want (e.g. cosmeticsview@.png,3470SQL.txt):

var match = Regex.Match(strAttachment, @"\$(.*)");
if (!match.Success) { return; }

then strip the characters you don't want. Define a list like this somewhere:

List<char> invalidChars = new List<char> { '@' };

In my example I only added the @.

Now just remove those characters:

var val = string.Join("",
    match.Groups[1].Value
        .Where(c => !invalidChars.Contains(c))
);

Here is a Regex 101 to prove the Regex I provided.

于 2013-10-29T12:17:20.547 回答