Attila
Attila

Reputation: 308

Regex to replace any character at a given position

I would like to replace one single character to a different one, which is in a specific position in the string. Example:

This is a test string! Now comes a different one! And yet an another one to demonstrate what I want! Hello there! How can I achieve to replace all exclamation mark to point!

I know that my character is on the 21st position, therefore I tried: .{21}(.)\K(.*?\1)+ The first capturing group has the character I want, and I can utilize \K to start from the last match. But then, how can I match the rest of the string?

The desired output would be: This is a test string. Now comes a different one. And yet an another one to demonstrate what I want. Hello there. How can I achieve to replace all exclamation mark to point. Thanks in advance!

Upvotes: 1

Views: 999

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You may use

^.{21}\K.

Or, if there are line breaks,

(?s)^.{21}\K.

See the regex demo

Details

  • (?s) - a dotall modifier that makes . match line break chars, too
  • ^ - start of string
  • .{21} - any 21 chars
  • \K - match reset operator
  • . - any one char.

Note that in many cases you may just use a group and backreference, ^(.{21}). -> $1<<YOUR_REPLACEMENT_STRING>>.

Upvotes: 1

Related Questions