简体   繁体   English

正则表达式匹配最后一个空格字符

[英]Regex to match last space character

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. 我使用的是JavaScript和经典的ASP。

I have a long string of text which I trim to 100 characters. 我有一长串文字,我修剪为100个字符。 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. 我想删除最后一个字符以避免拼写错误,如果修剪由于100个字符限制而剪切一个单词。

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

Anybody with ideas? 有想法的人吗? Thanks. 谢谢。

根据我的理解,你需要删除最后一个空格及其后的所有内容,对吧?

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

Try a lookahead assertion : 尝试一个先行断言

/ (?=[^ ]*$)/

And for arbitrary whitespace characters: 对于任意空白字符:

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

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 ] . 请注意,将空格放在字符类中是不必要的,除非您想匹配多个空格字符,例如制表符[\\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 ( $ ).". 正则表达式的意思是:“至少一个空格,以及它后面的任何非空格字符( \\S* ),在行的末尾( $ )。”

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. 作为副作用,字符串在末尾被修剪。

正则表达式/^.+ [^ ]*$/将仅匹配一行的最后一个空格。

Using "classic" REs, what you'd want would be " [^ ]*$" -- ie a space character followed by an arbitrary number of non-space characters followed by the end of the line. 使用“经典”RE,您想要的是" [^ ]*$" - 即空格字符后跟任意数量的非空格字符,后跟行尾。 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. 如果要将“单词”限制为包含字母,可以使用: " [^A-Za-z]*$"

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. 另请注意,无论哪种方式,如果一个单词恰好以第100个字符结尾,这将匹配它之前的空格,因此您将删除最后一个单词。 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. 如果你想防止这种情况,你(可能)想要查看你剪掉的第一个字符,如果它是空格,不要从缓冲区中删除任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM