This is my regex pattern: [!@#$%^&*().{}/-]
. I want to replace all the occurrences of these characters except the last occurrence. Please help me. Thanks.
Asked
Active
Viewed 382 times
-2

Wiktor Stribiżew
- 607,720
- 39
- 448
- 563

user318197
- 333
- 2
- 5
- 25
-
1Look into what a _positive lookahead_ is, you can replace patterns where there may exist a matching pattern infront of it. eg `[!@#$%^&*().{}\/-](?=.*[!@#$%^&*().{}\/-])` – Scuzzy Oct 04 '19 at 07:33
-
1There is no replacing in pure regex, you need to specify what regex engine you are using. – ruohola Oct 04 '19 at 07:34
-
I’m using C# framework – user318197 Oct 04 '19 at 07:35
-
1Great, so please share your current code that fails. – Wiktor Stribiżew Oct 04 '19 at 07:52
2 Answers
0
Something like that might help:
[!@#$%^&*().\{\}\/\-](?=.*[!@#$%^&*().\{\}\/\-])
(?=.*[!@#$%^&*().\{\}\/-])
is a positive lookahead ((?=
starts the positive lookahead). Meaning the pattern only matches if there is another of these characters somewhere ahead.
[!@#$%^&*().\{\}\/\-]
your pattern that should be matched (some escapes would be needed)
(?=
start of psotive lookahead (we need this after)
.*
any number of arbitrary characters.
[!@#$%^&*().\{\}\/\-]
again your pattern
)
end of positive lookahead
The important part is that the lookahead is not part of the matched string as such.

Lutz
- 612
- 3
- 8
0
For an “universal” solution I propose you to do this:
[a-z]*([a-z])
Replaced by:
$1
Adjust this solution for your case and language. You don’t need lookaheads

YOGO
- 531
- 4
- 5