javascript 拆分包含两者的字符串中的数字和字母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9742110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Splitting numbers and letters in string which contains both
提问by Ilya Tsuryev
I am trying to split following (or similar) string "08-27-2015 07:25:00AM". Currently I use
我正在尝试拆分以下(或类似的)字符串“08-27-2015 07:25:00AM”。目前我使用
var parts = date.split(/[^0-9a-zA-Z]+/g);
Which results in
这导致
["02", "27", "2012", "03", "25", "00AM"]
The problem is with the 00AM
part. I want it to be separated too. So the perfect result would be:
问题出在00AM
零件上。我也想分开 所以完美的结果是:
["02", "27", "2012", "03", "25", "00", "AM"]
回答by
If you're looking for sequences of letters or numbers, but not a sequence both mixed, you can do this...
如果您正在寻找字母或数字的序列,但不是两者混合的序列,您可以这样做......
"08-27-2015 07:25:00AM".match(/[a-zA-Z]+|[0-9]+/g)
resulting in...
导致...
["08", "27", "2015", "07", "25", "00", "AM"]
On either side of the |
, we have a sequence of one or more letters and a sequence of one or more numbers. So when it comes across a letter, it will gather all contiguous letters until it reaches a non-letter, at which point it gathers all contiguous numbers, and so on.
在 的两侧|
,我们有一个由一个或多个字母组成的序列和一个由一个或多个数字组成的序列。所以当它遇到一个字母时,它会收集所有连续的字母,直到遇到一个非字母,此时它会收集所有连续的数字,依此类推。
Any other character simply doesn't match so it doesn't become part of the result.
任何其他字符根本不匹配,因此它不会成为结果的一部分。
回答by amit_g
var date = "08-27-2015 07:25:00AM";
var parts = date.replace(/([AP]M)$/i, " ").split(/[^0-9a-z]+/ig);
var date = "05June2012";
var parts = date.replace(/([a-z]+)/i, " ").split(/[^0-9a-z]+/ig);
回答by nathanjosiah
If the date is always in that format you can use:
如果日期始终采用该格式,您可以使用:
var parts = date.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})\s([0-9]{2}):([0-9]{2}):([0-9]{2})(AM|PM)/).splice(1)
var parts = date.match(/([0-9]{2})-([0-9]{2})-([0-9]{4})\s([0-9]{2}):([0-9]{2}):([0-9]{2})(AM|PM)/).splice(1)
回答by Devin M
I would use a date library to parse the fields you want. That way you can handle multiple formats and not worry about parsing with regular expressions. While DateJSis a little old it performs well for parsing.
我会使用日期库来解析你想要的字段。这样您就可以处理多种格式,而不必担心使用正则表达式进行解析。虽然DateJS 有点旧,但它在解析方面表现良好。