-2

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

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
user318197
  • 323
  • 1
  • 5
  • 24

2 Answers2

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
  • 462
  • 2
  • 6
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
  • 511
  • 3
  • 5