我的目标是创建一个允许字母数字和任何特殊字符的正则表达式。
Example of accepted words:
Test 1
Test 123 !#@#
但是它不应该接受在单词之前或之后有空格的字符,或者多个空格,或者只有空格。
Example of unaccepted words:
Test 1 - spaces before
Test 1 - multiple spaces between
Test(spaces) - spaces after
(only spaces) - only spaces
答案 0 :(得分:2)
不是使用regexp,而是split
空格上的字符串,然后使用every
来确保结果中没有空字符串(这意味着在<某些地方的开头或结尾或之间)。
const tests = ['Test 1', ' Test 1', 'Test 123 !#@#', 'Test 1', 'Test ', ' '];
const passes = str => str . split(' ') . every(Boolean);
document.getElementById('results').textContent =
tests.map(str => `'${str}': ${passes(str)}`) . join('\n');
&#13;
<div id="results" style="white-space: pre; font-family: monospace; "></div>
&#13;
这个every(Boolean)
如何运作?它将每个元素转换为布尔值true / false值,并确保它们都转换为true。在JS中,空字符串将转换为false,因此这将检查每个元素不是否为空字符串。
答案 1 :(得分:1)
怎么样:
^[^ ]+( [^ ])*$
请根据您用于正则表达式的语言,将特殊字符转义。
答案 2 :(得分:0)
我认为你可以使用这样的正则表达式:
^[^ ]+( \S+)+$
答案 3 :(得分:0)
这应该可以解决问题:
^[\w]+( [\w]+)*$