Regex to match last space character

2019-02-05 04:54发布

问题:

I need some help. I am looking for a regex that would match the last space character in a string. I am using JavaScript and classic ASP.

I have a long string of text which I trim to 100 characters. I would like to remove the last character to avoid a spelling mistake if the trim cuts a word due to the 100 characters limit.

regex.replace(/[ ]$.*?/ig, '');

Anybody with ideas? Thanks.

回答1:

From my understanding, you need to remove the last space and everything after it, right?

 str = str.replace(/\s+\S*$/, "")


回答2:

Try a lookahead assertion:

/ (?=[^ ]*$)/

And for arbitrary whitespace characters:

/\s(?=\S*$)/


回答3:

That would be

/ +$/

A space character (), at least once (+), at the end of the line ($)

Note that putting the space in a character class is unnecessary, unless you want to match more than a space character, for example tabs [\t ].

To really match the single last space only, use / $/


EDIT: To cut off everything after the last space (thinking about it, this is what you actually seem to want, you can use:

regex.replace(/ +\S*$/ig, '');

where the regex means: "At least one space, and any non-whitespace characters after it (\S*), at the end of the line ($).".

This can only match the last bit of a line after the last space. As a side-effect, the string is trimmed at the end.



回答4:

The regex /^.+ [^ ]*$/ will match only the last space of a line.



回答5:

Using "classic" REs, what you'd want would be " [^ ]*$" -- i.e. a space character followed by an arbitrary number of non-space characters followed by the end of the line. The "non-space characters" might or might not fit your definition of a "word" though -- for example, it'll also prevent you from cutting a number in the middle. If you want to limit a "word" to containing letters, you could use: " [^A-Za-z]*$" instead.

Also note that either way, if a word happens to end at exactly the 100th character, this will match the space before it, so you'll remove that last entire word. If you want to prevent that, you'll (probably) want to look at the first character that you cut off, and if it's white space, don't remove anything from the buffer.