0

How can I replace all digits in URL after third slash, on characters #### with regexp? In this case, the number of # must correspond to the number of replaced digits. Numbers can be in more than one slash section. Also, the location of the digits is not fixed, but exactly after the third slash

Examples:

/path/to/something/1234/end
/path/to/something/12/1234/end

To:

/path/to/something/####/end
/path/to/something/##/####/end

I tried to use an expression, but it does not give the desired result:

"(?<=/)\\d+(?=/|$), #####"

This regexp is needed to implement the grok pattern in Logstash (gsub function).

P.s. Why after third slash? Because because the numbers can be at the beginning, but they do not need to be changed (/path/to_1/something/1234/end)

8
  • 2
    Try (?:\G(?!^)(?:(?=\d*/)|/)|^(?:/[^/]*){3}/)\K\d to replace with #. Or, maybe (?:\G(?!^)/?|^(?:/[^/]*){3}/)\K\d(?=\d*/) will be more precise. Commented May 18, 2022 at 10:43
  • The expression works on the example, but doesn't work on the real query regex101.com/r/7DXl5t/1 Commented May 18, 2022 at 12:15
  • And what is the "real query"? Is it anywhere in the question? Commented May 18, 2022 at 12:21
  • 1
    Then it is even simpler: (?:\G(?!^)|^(?:/[^/]*){3}/)\D*\K\d, see regex101.com/r/7DXl5t/3 Commented May 18, 2022 at 14:14
  • 1
    If it does not work, try to use (?:\G(?!^)|^((?:/[^/]*){3}/))(\D*)\d as regex and $1$2# as replacement. See this regex demo. Commented May 18, 2022 at 14:47

1 Answer 1

1

You can use

(?:\G(?!^)|^((?:/[^/]*){3}/))(\D*)\d

as regex and $1$2# as replacement.

See the regex demo.

Details:

  • (?:\G(?!^)|^((?:/[^/]*){3}/)) - end of the previous match (\G(?!^)) or (|) start of string + three occurrences of / and then zero or more non-slash shars and then a slash char captured into Group 1 (^((?:/[^/]*){3}/))
  • (\D*) - Group 2: any zero or more non-digits
  • \d - a digit

The replacement is a concatenation of Group 1 + Group 2 values and a # char.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.