以不同的格式提取字符串的数字和文本部分

时间:2022-09-13 14:01:07

I'm trying to put together a RegEx to split a variety of possible user inputs, and while I've managed to succeed with some cases, I've not managed to cover every case that I'd like to.

我正在尝试整合一个RegEx来分割各种可能的用户输入,虽然我已经设法在某些情况下成功,但我没有设法覆盖我想要的每一个案例。

Possible inputs, and expected outputs

可能的输入和预期的输出

"1 day" > [1,"day"]
"1day" > [1,"day"]
"10,000 days" > [10000,"days"]

Is it possible to split the numeric and text parts from the string without necessarily having a space, and to also remove the commas etc from the string at the same time?

是否可以从字符串中拆分数字和文本部分而不必有空格,同时还从字符串中删除逗号等?

This is what I've got at the moment

这就是我现在所拥有的

[a-zA-Z]+|[0-9]+

Which seems to split the numeric and text portions nicely, but is tripped up by commas. (Actually, as I write this, I'm thinking I could use the last part of the results array as the text part, and concatenate all the other parts as the numeric part?)

这似乎很好地分割了数字和文本部分,但是被逗号绊倒了。 (实际上,当我写这篇文章时,我想我可以使用结果数组的最后一部分作为文本部分,并将所有其他部分连接成数字部分?)

2 个解决方案

#1


1  

var test = [
    '1 day',
    '1day',
    '10,000 days',
];
console.log(test.map(function (a) {
  a = a.replace(/(\d),(\d)/g, '$1$2'); // remove the commas
  return a.match(/^(\d+)\s*(.+)$/);    // split in two parts
}));

#2


1  

This regular expression works, apart from removing the comma from the matched number string:

除了从匹配的数字字符串中删除逗号之外,此正则表达式仍然有效:

([0-9,]+]) *(.*)

You cannot "ignore" a character in a returned regular expression match string, so you will just have to remove the comma from the returned regex match afterwards.

您不能“忽略”返回的正则表达式匹配字符串中的字符,因此您只需要在之后从返回的正则表达式匹配中删除逗号。

#1


1  

var test = [
    '1 day',
    '1day',
    '10,000 days',
];
console.log(test.map(function (a) {
  a = a.replace(/(\d),(\d)/g, '$1$2'); // remove the commas
  return a.match(/^(\d+)\s*(.+)$/);    // split in two parts
}));

#2


1  

This regular expression works, apart from removing the comma from the matched number string:

除了从匹配的数字字符串中删除逗号之外,此正则表达式仍然有效:

([0-9,]+]) *(.*)

You cannot "ignore" a character in a returned regular expression match string, so you will just have to remove the comma from the returned regex match afterwards.

您不能“忽略”返回的正则表达式匹配字符串中的字符,因此您只需要在之后从返回的正则表达式匹配中删除逗号。