Javascript RegularExpression-匹配字符而不是数字

Javascript RegularExpression-匹配字符而不是数字,javascript,regex,Javascript,Regex,我想匹配一个字符串,后跟多个制表符和另一个字符串。第二个字符串不能有任何数字 所以我想要'someText\t\tsomeText2'->someText&sometext2 我有以下JavaScript: var linePattern = /(^[^\s].+?)\t+([^\d].+)/ var regexp = new RegExp(linePattern); var parts = 'someText\t\t1234'.match(regexp); 不确定它为什么会匹配…它不应该匹配

我想匹配一个字符串,后跟多个制表符和另一个字符串。第二个字符串不能有任何数字

所以我想要'someText\t\tsomeText2'->someText&sometext2

我有以下JavaScript:

var linePattern = /(^[^\s].+?)\t+([^\d].+)/
var regexp = new RegExp(linePattern);
var parts = 'someText\t\t1234'.match(regexp);

不确定它为什么会匹配…它不应该匹配。

因为最后一个
+
也会匹配数字

^(.*?)\t\t+(\D+)$

你的正则表达式

    (^             [^\s]               .+?)               \t+                          ([^\d].+)
                     ^                  ^                 ^
   Start           Matches the   Matches all the chars  Matches only the first tab  since the second character must not be a non-digit character. So `[^\d]` matches the second tab. and the `.+` matches all the chars upto the last. Finally you got a match.
            first non-space      upto the  first tab
              character.
代码:

> var linePattern = /^(.*?)\t+(\D+)$/;
undefined
> var regexp = new RegExp(linePattern);
undefined
> var parts = 'someText\t\t1234'.match(regexp);
undefined
> parts
null
> var parts = 'someText\t\tfoo'.match(regexp);
undefined
> parts
[ 'someText\t\tfoo',
  'someText',
  'foo',
  index: 0,
  input: 'someText\t\tfoo' ]
([^\d].+)
实际上是在字符串中第一个匹配的制表符之后匹配制表符(除数字以外的任何字符),然后贪婪的
+
将继续使用并匹配字符串中的数字

此外,这里不需要使用RegExp对象,一个正则表达式文本就足够了

您可以按如下方式修改正则表达式和语法:

var re = /^(.*?)\t+(\D+)$/
var parts = str.match(re);
注意:在此处同时使用字符串开头
^
和字符串结尾
$
锚定非常重要。

供将来参考:是测试和计算正则表达式模式的好工具。
var re = /^(.*?)\t+(\D+)$/
var parts = str.match(re);