I have a string like following:
string strAttachment = "3469$cosmeticsview@.png,3470SQL.txt";
i want this:
cosmeticsview.png,SQL.txt
i try this:
var result = Regex.Replace(strAttachment, @"\d+@+$", "");
Response.Write(result);
but not work.
i think causes this problem is $ symbol.
Edit
I want remove digits also
try escaping it like \\$
it's reserved in Regex to indicate the end of a line
Also, the @+
isn't needed - that's not how regex works. To get your desired result you want:
\\d+\\$
then use a Replace for the @
:
var result = Regex.Replace(strAttachment, @"\d+$", "").Replace("@","");
You have two problems here - first is escaping of special regex symbols (end of line in your case). And second one is wrong pattern - your current solution tries to match @
right after digits:
one or more @ character
|
| end of line
| |
\d+@+$
|
one or more digit
That will be matched by hello1234@
which, of course, not your case. You want to remove either digits with dollar sign, or @ character. Here is correct pattern:
one optional $ character
|
| OR
| |
\d+\$?|@
| |
| @ character
|
one or more digit
Here is code:
string strAttachment = "3469$cosmeticsview@.png,3470SQL.txt";
var result = Regex.Replace(strAttachment, @"\d+\$?|@", "");
Alternatively, if you just want to remove any digits, dollars and @ from your string:
var result = Regex.Replace(strAttachment, @"[\d\$@]+", "");
I think you're complicating this by trying to make a single pass. First get the part of the string you want (eg 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.