neptr
neptr

Reputation: 17

Regex to truncate all words to a maximum word length?

EDITED: How can I use RegEx to match all the words in a sentence and truncate them to a maximum length of 3 letters each? I'm using a search/replace function.

As an example I would like to take this sentence:

RegEx to trim all words

and return this:

Reg to tri all wor

but instead I get this:

Reg

I'm using Advanced Renamer with the Replace function:

Search:

^([^\d\W]{3}).*?$

Replace:

$1

Any help would be appreciated!

Upvotes: 0

Views: 1055

Answers (3)

The fourth bird
The fourth bird

Reputation: 163517

The docs of Advanced Renamer states that the PCRE is used which supports \K

In the replacement use an empty string.

[^\d\W]{3}\K[^\d\W]+
  • [^\d\W]{3} Match 3 word chars except digits
  • \K Forget what was matched
  • [^\d\W]+ Match 1+ word chars except digits

Regex demo

Upvotes: 1

John
John

Reputation: 579

Find: (\w{0,3})[\w]*

  • (\w{0,3}) gets first 3 characters ([a-zA-Z0-9_]) of a word (goes into capture group 1)
  • [\w]* gets the rest of the characters so we can forget about them

Replace with: \1 (first capture group)

See Regex101

Upvotes: 0

Jeff Y
Jeff Y

Reputation: 2466

The problem is that you are matching the whole line with that regex and thus truncating the whole line to its first 3 characters. You don't say what application you're doing the search/replace with. Please edit your question to specify that. But it looks like what you want instead is something like:

([^\d\W]{3})[^\d\W]*

And you want to use a "replace all" option.

Upvotes: 0

Related Questions