-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
  • 607,720
  • 39
  • 448
  • 563
user318197
  • 333
  • 2
  • 5
  • 25

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
  • 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