riallus
riallus

Reputation: 21

Regex Capture Group substring

Trying to use Regex in Notepad++. I'd like to have the following happen:

FirstName: Jonathan

Replaced to:

FirstName: Jona

I've tried the following:

Find Statement

FirstName:(.*)

Replace Statement:

FirstName:\1

In order to put it into a captured group. But now I need that captured group to be truncated/substring so it's just the first four characters. When I do the replace, it replaces the full string just fine, but I'm not clear how to get just the first four characters of the capture group. I've tried (.*){4} but that returns nothing.

Thank you!

Upvotes: 2

Views: 4990

Answers (4)

mickmackusa
mickmackusa

Reputation: 47991

This pattern will only bother processing lines with excess length to truncate.

My pattern will not only outperform the other answers in terms of step-count/efficiency, but it will also not bother with any references or text in the replacement field.

Use this: (Pattern Demo)

Find: FirstName: .{4}\K.+
Replace: [nothing]

*Note, the \K means "start matching from this point". The .+ will stop at the end of each line.

Upvotes: 0

user557597
user557597

Reputation:

If it's at the beginning of the line and line oriented,
or the only line item, this would work.

Find: (?im)^[^\S\r\n]*(firstname:)[^\S\r\n]*([a-z]{0,4}|.{0,4}).*
Replace: FirstName $1

If it's in the middle of the string, it would take more effort.
Have to see some examples of that because would have to use pseudo-anchors.

Upvotes: 0

c0d3rman
c0d3rman

Reputation: 667

I'm not sure there is a way to access just a part of a matched group, but you can instead only match the part you want.

Your new find statement would capture only the first 4 characters but still match the rest:

FirstName: (.{4}).*?$

Which translates to "find the string 'FirstName: ', then remember the next four characters, and then keep going till the end of the line."

Your replace statement would be almost the same as before (I included a space after FirstName):

FirstName: \1

Upvotes: 2

Toto
Toto

Reputation: 91498

Here is a way to go:

  • Find what: (FirstName:.{1,4}).*?$
  • Replace with: $1

Upvotes: 1

Related Questions