Search code examples
regextrim

trim spaces on captured group regex


after searching everywhere, How can whitespace be trimmed from a Regex capture group?, seems to have the closest thing, and I can almost taste it, but still no cigar.... So here goes, for my very first post to StackOverflow.....

I am trying to capture Exactly 27 characters of a string (for reasons that really don't matter).

So I used regex: .{27}

on this string "Joey Went to the Store and found some great steaks!"

the result was "Joey Went to the Store and "

Bingo exactly 27 characters. But that result is causing errors in my program because of the trailing space. So now I need to also take that result and trim the space after "and " to return the result without the trailing space. the final result needs to be "Joey Went to the Store and".

here's the kicker, I need it to all work from a single regex because the application can only apply 1 regex (really dumb program, but I'm stuck with it).


Solution

  • Take a look at this regex:

    ^.{26}[^\s]?
    

    It will match 26 characters starting from beginning of line and will match the 27th only if it is not a white space character. See the demo below for more details.

    Regex Demo