Home > Mobile >  RegEx - Limit no of chars for each value in a separated string
RegEx - Limit no of chars for each value in a separated string

Time:12-15

I'm trying to make a RegEx to limit number of characters for each column in a separated list.

So in list with 5 columns; and would like to limit each column to 3 characters:

ABC;DE FGHIJ;KLMNOPQRS;T UVWX;YZ

The result I would like:

ABC;DE ;KLM;T U;YZ

Tried different look ahead but can figure it out :-(

CodePudding user response:

If you have a regex replacement available to you, you may try the following operation:

Find:    ([^;]{3})[^;] ?(;|$)
Replace: $1$2

The pattern matches:

  • ([^;]{3}) the first 3 characters in $1
  • [^;] ? then match 1 more characters until reaching the nearest
  • (;|$) either ; or the end of the string (and capture ; in $2 if present)

We then replace with $1$2 to effectively trim off the unwanted characters.

Here is a link to a working demo.

CodePudding user response:

Another option is to match all the parts you need, using the following regex:

(?<=^|;)[^;]{1,3}

This will match:

  • [^;]{1,3} every non-semicolon, preceeded by
  • (?<=^|;) either start of string or semicolon

Check the demo here.

CodePudding user response:

You can use

s/((?:;|^)[^;]{1,3})[^;]*/$1/g

Demo

  • Related