Home > OS >  RegExp - find 1,2,3,6,7,8 and 9th letter from the end of the string
RegExp - find 1,2,3,6,7,8 and 9th letter from the end of the string

Time:07-25

I'm new to regular expressions and trying to figure out which expression would match 1,2,3 and 6,7,8,9th letter in the string, starting from the end of the string. It would also need to include \D (for non-digits), so if 3rd letter from the end is a number it will exclude it.

Example of a string is

Wsd-kaf_23psd_trees32rap

So the result should be:

reesrap

or for

Wsd-kaf_23psd_trees324ap

it would be

reesap

This

(?<=^.{9}).*

gives me last 9 chars, but that's not really what I want.

Does anyone knows how can I do that?

Thanks.

CodePudding user response:

You could try to use alternations to find all characters upto the position that holds 9 character untill the end or consecutive digits:

(?:^.*(?=.{9})|\d )

See an online demo. Replace with empty string.


  • (?: - Open non-capture group;
    • ^.* - Any 0 characters (greedy), upto;
    • (?=.{9}) - A positive lookahead to assert position is followed by 9 characters;
    • | - Or;
    • \d - 1 digits.

If, however, your intention was to match the characters seperately, then try:

\D(?=.{0,8}$)

See an online demo. Any non-digit that has 0-8 characters upto the end-line character.

  • Related