Validation
No Whitespace Regex
API keys, tokens, product codes and many identifiers must never contain whitespace, and a stray space copied from an email is a common cause of failed logins. This pattern accepts one or more non-whitespace characters and nothing else, anchored at both ends. Any space, tab or newline, including one at the very start or end of the value, makes the input fail. Any other character, such as letters, digits, dashes or symbols, is allowed. Use it as a quick sanity check on pasted secrets and codes, or combine it with a length check for stricter formats.
Pattern (JavaScript)
/^\S+$/Starts at the start of the line/string, then one or more non-whitespace characters, then the end of the line/string.
Examples
Matches
- ✓ abc123
- ✓ token-XYZ_9
- ✓ a!b@c
Does not match
- ✗ a b
- ✗ tab here
- ✗
Try it
0 matches (JavaScript engine)
abc123
token-XYZ_9
a!b@c
a b
tab here
Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /^\S+$/g;
const text = "abc123";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'^\S+$')
text = 'abc123'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/^\S+$/';
$text = 'abc123';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^\\S+$");
String text = "abc123";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^\S+$`)
text := "abc123"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"^\S+$");
var text = "abc123";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"^\S+$").unwrap();
let text = "abc123";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /^\S+$/
text = 'abc123'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- Should I reject the value or trim it?
- For pasted tokens, trimming leading and trailing spaces first is friendlier. Use this pattern after trimming to catch spaces in the middle.
- Does it reject an empty string?
- Yes. The plus quantifier requires at least one character. Use \S* if empty input is acceptable.
- Which characters count as whitespace?
- In JavaScript, \s covers spaces, tabs, line breaks and Unicode space characters such as the non-breaking space. All of them are rejected here.