Javascript拆分正则表达式问题 [英] Javascript split regex question

查看:160
本文介绍了Javascript拆分正则表达式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好我正在尝试我认为在Javascript中相当容易的正则表达式,但是给了我很多麻烦。
我希望能够通过javascript分割来分割日期,分别是' - ','。','/'和''。

hello I am trying what I thought would be a rather easy regex in Javascript but is giving me lots of trouble. I want the ability to split a date via javascript splitting either by a '-','.','/' and ' '.

var date = "02-25-2010";
var myregexp2 = new RegExp("-."); 
dateArray = date.split(myregexp2);

这个正确的正则表达式是什么,所有帮助都很棒。

What is the correct regex for this any and all help would be great.

推荐答案

你需要把你希望拆分的字符放在字符类,它告诉正则表达式引擎这些字符中的任何一个都匹配。为了您的目的,这看起来像:

You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:

date.split(/[.,\/ -]/)

虽然破折号在字符类中作为范围说明符具有特殊含义(即 [az] [abcdefghijklmnopqrstuvwxyz] 相同,如果你把它作为课程中的最后一件事,它被认为是一个文字破折号并且不需要转义。

Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.

要解释为什么你的模式不起作用, /-./ 告诉正则表达式引擎匹配文字短划线字符后跟任何字符(是通配符常用表达)。对于02-25-2010,每次遇到-2时它会分开,因为短划线匹配且点匹配2。

To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".

这篇关于Javascript拆分正则表达式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆