如何在PostgreSQL中匹配句子中的最后两个单词? [英] How can I match the last two words in a sentence in PostgreSQL?
问题描述
已经尝试了一段时间,以匹配句子的最后一个单词:
Have been trying for a while, to match the last word of a sentence:
select regexp_matches('My name is Harry Potter', '[^ ]+$');
返回{Potter}
returned {Potter}
尝试匹配最后两个单词:
to try to match the last two words:
select regexp_matches('My name is Harry Potter', '[^ ]\s+[^ ]+$');
失败。
select regexp_matches('My name is Harry Potter', '(.*?)\s+(.*?)$');
也未按预期词写。
有什么见解?
推荐答案
您应该在模式,因为PostgreSQL实例的 standard_conforming_strings
参数似乎已关闭。请参见 PostgreSQL 9.5.3文档:
You should use double escaping in the pattern since it seems the standard_conforming_strings
parameter of your PostgreSQL instance is turned off. See PostgreSQL 9.5.3 Documentation:
standard_conforming_strings(布尔值)
这将控制普通字符串文字('...')是否按SQL标准指定按字面对待反斜杠。从PostgreSQL 9.1开始,默认设置为on(以前的版本默认为off)。
standard_conforming_strings (boolean)
This controls whether ordinary string literals ('...'
) treat backslashes literally, as specified in the SQL standard. Beginning in PostgreSQL 9.1, the default is on (prior releases defaulted to off).
因此,您需要使用
'[^ ]+\\s+[^ ]+$'
^^
或
'\\S+\\s+\\S+$'
此处,
-
[^] +
-除空格以外的1个或多个字符(如果\\S
,则为任何非空白) -
\\s +
-1个或多个空格 -
[^] +
-除空格以外的1个或多个字符(如果使用\\S
,则为任何非空白) -
$
-字符串锚点的结尾。
[^ ]+
- 1 or more characters other than a space (any non-whitespace if\\S
is used)\\s+
- 1 or more whitespaces[^ ]+
- 1 or more characters other than a space (any non-whitespace if\\S
is used)$
- end of string anchor.
这篇关于如何在PostgreSQL中匹配句子中的最后两个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!