简体   繁体   English

如何匹配字符串的开头和结尾?

[英]How to match the start and end of a string?

I try to match space at the start and the end of string, I tried many regexes but nothing worked, this is my basic regex: 我尝试在字符串的开头和结尾处匹配空格,我尝试了许多正则表达式,但没有任何效果,这是我的基本正则表达式:

^\s\s$

Any help or hint please? 有任何帮助或提示吗? I would like to not give me the answer directly, just useful hints will be useful. 我不想直接给我答案,只有有用的提示才有用。

Your current regex will match things like 2 spaces, because that's what your regex says: 您当前的正则表达式将匹配2个空格,因为这是您的正则表达式所说的:

start of string, whitespace, whitespace, end of string 字符串开头,空格,空格,字符串结尾

To match spaces both at the start and at the end, you need to use the | 要在开头和结尾都匹配空格,您需要使用| to mean "or". 表示“或”。 If the whitespace is either at the start or the end, we match it: 如果空格是开头还是结尾,我们将其匹配:

^\s|\s$

If you want to match multiple spaces: 如果要匹配多个空格:

^\s+|\s+$

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

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