[英]Why does using a String.split(regex) include an empty string at the beginning of resulting array?
I have a string data
that is a numbered list (eg "1.Line 1\n2. Line 2\nLine 2 Continued\n3. Line 3"
) I tried making a regex that splits the string into ["Line 1\n", "Line 2\nLine 2 Continued\n", "Line 3"]
and I made this regex const reg = /\d+\./gm
.我有一个字符串
data
,它是一个编号列表(例如"1.Line 1\n2. Line 2\nLine 2 Continued\n3. Line 3"
)我尝试制作一个将字符串拆分为["Line 1\n", "Line 2\nLine 2 Continued\n", "Line 3"]
的正则表达式["Line 1\n", "Line 2\nLine 2 Continued\n", "Line 3"]
我做了这个正则表达式const reg = /\d+\./gm
。 When I use the following regex via data.split(reg)
, I do see the elements in the desired output, but I also see a leading ""
element in the beginning of the array - ["","Line 1\n", "Line 2\nLine 2 Continued\n", "Line 3"]
.当我通过
data.split(reg)
使用以下正则表达式时,我确实看到了所需 output 中的元素,但我还在数组的开头看到了一个前导""
元素 - ["","Line 1\n", "Line 2\nLine 2 Continued\n", "Line 3"]
. Any explanation as to why this ""
exists?关于为什么这个
""
存在的任何解释? Any way to prevent this from showing besides just slicing the array, or even the proper regex if this one is wrong.除了对数组进行切片之外,任何防止这种情况出现的方法,或者如果这个是错误的,甚至是正确的正则表达式。
Your initial empty string exists because your split applies also to the first number 1 "1.Line 1\n
, which will separate everything after your regex ( Like 1\n
) from anything before ( ""
).您的初始空字符串存在,因为您的拆分也适用于第一个数字 1
"1.Line 1\n
,它将您的正则表达式( Like 1\n
)之后的所有内容与之前的任何内容( ""
)分开。
In order to fix this problem, you can try making your regex more specific, so that it will apply the split beginning from the second line.为了解决这个问题,您可以尝试使您的正则表达式更具体,以便它将应用从第二行开始的拆分。 One way of doing this is adding up the
\n
to the regex (which can be found only from the second line on as needed).这样做的一种方法是将
\n
添加到正则表达式(只能根据需要从第二行中找到)。
const reg = \\n/\d+\./gm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.