简体   繁体   English

字符串开头和结尾没有空格

[英]No white space in the beginning and at the end of string

In my Angular application (Typescript)I want to check an input against white spaces in the beginning and at the end of the inserted value by the user.在我的 Angular 应用程序(Typescript)中,我想在用户插入的值的开头和结尾检查input是否有空格。

The following Regex ^[^\\s].+[^\\s]$ and its RegExp equivalent /[^\\s].+[^\\s]/ is the most common answer I found.以下正则表达式^[^\\s].+[^\\s]$及其等效的/[^\\s].+[^\\s]/RegExp /[^\\s].+[^\\s]/是我发现的最常见的答案。 But the test function of this regex does not return correct boolean.但是这个正则表达式的test函数没有返回正确的布尔值。

What is the correct RegExp that returns false if a string contains whitespaces in the beginning, at the end or both?如果字符串在开头、结尾或两者都包含空格,则返回 false 的正确 RegExp 是什么?

 function myFunction(){ var myStr=document.getElementById("reader").value; var regex1=/[^\\s].+[^\\s]/; var regex2=new RegExp('[^\\s].+[^\\s]','i'); var result1=regex1.test(myStr); var result2=regex2.test(myStr); document.getElementById("writer1").value=result1; document.getElementById("writer2").value=result2; }
 <input id="reader" type="text" placeholder="string" onChange="myFunction()"/> <p> regex:<input type="text" id="writer1"/></p> <p> with constructor:<input type="text" id="writer2"/></p>

Using the first pattern ^[^\\s].+[^\\s]$ you string must have at least 3 characters because the negated character class requires a match and .+ will match 1+ times any char except a newline.使用第一个模式^[^\\s].+[^\\s]$您的字符串必须至少有 3 个字符,因为否定字符类需要匹配,而.+将匹配除换行符之外的任何字符的 1+ 次。

The second pattern [^\\s].+[^\\s] is not anchored and will also allow partial matches.第二个模式[^\\s].+[^\\s]没有锚定,也允许部分匹配。

If you also want to match a or aa you could use a negative lookaround to assert that the string does not end with a space or tab and start the match with a non whitespace char.如果您还想匹配aaa您可以使用否定环顾来断言字符串不以空格或制表符结尾,并以非空白字符开始匹配。

^(?!.*[ \t]$)\S.*$
  • ^ Start of string ^字符串开始
  • (?!.*[ \\t]$) Negative lookahead, assert what is on the right is not a space or tab at the end of the string (?!.*[ \\t]$)否定前瞻,断言右边不是字符串末尾的空格或制表符
  • \\S Match a non whitespace char \\S匹配一个非空白字符
  • .* Match any char 0+ times except a newline .*匹配任何字符 0+ 次,除了换行符
  • $ End of string $字符串结尾

Regex demo正则表达式演示

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

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