简体   繁体   中英

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.

The following Regex ^[^\\s].+[^\\s]$ and its RegExp equivalent /[^\\s].+[^\\s]/ is the most common answer I found. But the test function of this regex does not return correct boolean.

What is the correct RegExp that returns false if a string contains whitespaces in the beginning, at the end or both?

 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.

The second pattern [^\\s].+[^\\s] is not anchored and will also allow partial matches.

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.

^(?!.*[ \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
  • \\S Match a non whitespace char
  • .* Match any char 0+ times except a newline
  • $ End of string

Regex demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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