0

I'm trying to use a regex replace each character after a given position (say, 3) with a placeholder character, for an arbitrary-length string (the output length should be the same as that of the input). I think a lookahead (lookbehind?) can do it, but I can't get it to work.

What I have right now is:

  • regex: /.(?=.{0,2}$)/
  • input string: 'hello there'
  • replace string: '_'
  • current output: 'hello th___' (last 3 substituted)

The output I'm looking for would be 'hel________' (everything but the first 3 substituted).

I'm doing this in Typescript, to replace some old javascript that is using ugly split/concatenate logic. However, I know how to make the regex calls, so the answer should be pretty language agnostic.

EJSawyer
  • 409
  • 5
  • 5

1 Answers1

2

If you know the string is longer than given position n, the start-part can be optionally captured

(^.{3})?.

and replaced with e.g. $1_ (capture of first group and _). Won't work if string length is <= n.

See this demo at regex101


Another option is to use a lookehind as far as supported to check if preceded by n characters.

(?<=.{3}).

See other demo at regex101 (replace just with underscore) - String length does not matter here.


To mention in PHP/PCRE the start-part could simply be skipped like this: ^.{1,3}(*SKIP)(*F)|.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
  • 1
    The length is completely arbitrary -- could be empty, 2 characters, or 50. The second regex (with lookbehind, I had a feeling that was going to be involved) solved it, thanks! – EJSawyer Oct 19 '22 at 21:42