regex一个单词的最后字符

时间:2021-10-14 20:48:48

I'm attempting to match the last character in a WORD.

我在尝试匹配一个单词的最后一个字符。

A WORD is a sequence of non-whitespace characters '[^\n\r\t\f ]', or an empty line matching ^$.

一个单词是一个非空字符序列”[^ t \ n \ r \ \ f]”,或一个空行匹配^ $。

The expression I made to do this is: "[^ \n\t\r\f]\(?:[ \$\n\t\r\f]\)"

表达我是:“[^ \ n \ t f \ r \]\(?:[\ $ f \ n \ t \ r \]\)”

The regex matches a non-whitespace character that follows a whitespace character or the end of the line.

regex匹配一个空格字符或行尾的非空白字符。

But I don't know how to stop it from excluding the following whitespace character from the result and why it doesn't seem to capture a character preceding the end of the line.

但是我不知道如何阻止它从结果中排除下面的空格字符,以及为什么它似乎没有捕获行尾之前的字符。

Using the string "Hi World!", I would expect: the "i" and "!" to be captured.

使用字符串“Hi World!”,我希望“我”和“!”能够被抓住。

Instead I get: "i ".

相反,我得到的是“我”。

What steps can I take to solve this problem?

我可以采取什么措施来解决这个问题?

1 个解决方案

#1


3  

Note that a non-capturing group (?:...) in [^ \n\t\r\f](?:[ \$\n\t\r\f]) still matches (consumes) the whitespace char (thus, it becomes a part of the match) and it does not match at the end of the string as the $ symbol is not a string end anchor inside a character class, it is parsed as a literal $ symbol.

注意,无组(?…)[^ \ n \ t f \ r \](?[\$\ $\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \

You may use

你可以用

\S(?!\S)

See the regex demo

看到regex演示

The \S matches a non-whitespace char that is not followed with a non-whitespace char (due to the (?!\S) negative lookahead).

\S与非空白字符匹配,而非空白字符(由于(?!\S)为负的lookahead)。

#1


3  

Note that a non-capturing group (?:...) in [^ \n\t\r\f](?:[ \$\n\t\r\f]) still matches (consumes) the whitespace char (thus, it becomes a part of the match) and it does not match at the end of the string as the $ symbol is not a string end anchor inside a character class, it is parsed as a literal $ symbol.

注意,无组(?…)[^ \ n \ t f \ r \](?[\$\ $\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \

You may use

你可以用

\S(?!\S)

See the regex demo

看到regex演示

The \S matches a non-whitespace char that is not followed with a non-whitespace char (due to the (?!\S) negative lookahead).

\S与非空白字符匹配,而非空白字符(由于(?!\S)为负的lookahead)。