I need to find the space character at or before the nth character of a string.
Example, assuming that n is 20: in the string
Find one space in the right place
^ ^ ^ ^
0 10 M 20
the h is in the 20th position, int this case I need to find the first space before the 20th position, the one before the word "the" in 18th position, just over the M.
I can find the nth character using positive lookbehinds like
(?<=.{80}).
but then I need to go back until I find the first space character and I don't know how.
I'm using notepad++ which doesn't support variable length lookbehinds, if possible I'd like an answer allowing me to use the regex also in notepad++. Thanks.
You can use this regex (inside but excluding quotes):
"^.{1,19} "
Note the space at the end.
I have tested this with Notepad++ 6.1.5 (the latest version at time of posting). According to the feature list, the regex is PCRE compatible (look-behind works, but fixed width only). The regex above doesn't work on an older version I current have (Notepad++ 5.9).
Since you need to replace the space with something else, you may want to use capturing group to preserve the text and replace only the space (inside but excluding quotes):
"^(.{1,19}) " (Find)
"\1replace_space" (Replace)
Note: The regex will search for the space before or at the 20th character. If you want the space to be strictly before 20th character, change 19 to 18.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With