[英]Match everything except the digit and space in the very beginning
The target string looks like a number followed by a space and then followed by one or more letters, eg 1 Foo
or 2 Foo bar
.目标字符串看起来像一个数字后跟一个空格,然后是一个或多个字母,例如1 Foo
或2 Foo bar
。
I can use [^\d\s].+
, but it doesn't work for single letters, eg 3 A
.我可以使用[^\d\s].+
,但它不适用于单个字母,例如3 A
。
What can be done here?这里可以做什么?
https://regexr.com/6io06 https://regexr.com/6io06
The workaround I use currently is to use replacing instead of matching.我目前使用的解决方法是使用替换而不是匹配。
from \d\s(.+)
to $1
But as a purist I prefer to use replacing if and only if we don't mean "replace something with nothing".但作为一个纯粹主义者,当且仅当我们的意思不是“用什么都不替换”时,我更喜欢使用替换。 When we need to replace something with nothing, I would prefer to use matching.当我们需要用什么替换一些东西时,我更愿意使用匹配。
Just remove the square brackets.只需删除方括号即可。 The square brackets alone indicate "any of this set", so you are matching either \d
or \s
.方括号单独表示“此集合中的任何一个”,因此您匹配的是\d
或\s
。 When you also add a ^
inside you are not indicating the beginning of the string, but you are negating the set.当您还在内部添加^
时,您并不是在指示字符串的开头,而是在否定集合。 So, summing up, your regular expression means:因此,总而言之,您的正则表达式意味着:
Match a single character that may be everything except a digit and a white space, then match everything.匹配一个字符,它可以是除数字和空格之外的所有内容,然后匹配所有内容。
If you remove the square brackets you will match \d
followed by \s
, and the ^
symbol will mean "beginning of the string".如果您删除方括号,您将匹配\d
后跟\s
,并且^
符号将表示“字符串的开头”。
/^\d\s(.+)/
I prefer using a regex replacement here:我更喜欢在这里使用正则表达式替换:
var input = ["1 Foo", "2 Foo Bar", "No Numbers Here"]; var output = input.map(x => x.replace(/^\d+ /, "")); console.log(output);
If I didn't misread your question, this might be what you want:如果我没有误读你的问题,这可能就是你想要的:
exclude capture the number and space at the beginning exclude 捕获开头的数字和空格
https://regexr.com/6io1m https://regexr.com/6io1m
(?!^\d+)(?!\s+).*
This matches 1 Foo Bar
to Foo Bar
and 3 A
to A
这匹配1 Foo Bar
到Foo Bar
和3 A
到A
You don't have to use replace.您不必使用替换。 You can optionally match a digit and a space at the start of the string with ^(?:\d+ )?
您可以选择将字符串开头的数字和空格与^(?:\d+ )?
and capture the rest of the line in group 1 that starts with a letter.并捕获组 1 中以字母开头的行的 rest。
Note that if you want to use \s
that is could also match a newline.请注意,如果你想使用\s
那也可以匹配换行符。
^(?:\d+ )?([A-Za-z].*)
const regex = /^(?:\d+ )?([A-Za-z].*)/; ["1 Foo", "2 Foo bar", "Test", "3 A", "-test-"].forEach(s => { const m = s.match(regex); if (m) console.log(m[1]) });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.