Javascript Javascript拆分正则表达式问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3559883/
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
Javascript split regex question
提问by Craig
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 ' '.
你好,我正在尝试我认为在 Javascript 中相当简单的正则表达式,但给我带来了很多麻烦。我希望能够通过 javascript 将日期拆分为 '-'、'.'、'/' 和 ' '。
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.
什么是正确的正则表达式,任何和所有帮助都会很棒。
回答by Daniel Vandersluis
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(/[.,\/ -]/)
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.
尽管破折号在字符类中作为范围说明符具有特殊含义(即[a-z]与 相同[abcdefghijklmnopqrstuvwxyz]),但如果您将其作为类中的最后一项,则它被认为表示文字破折号并且不需要转义。
To explain why your pattern didn't work, /-./tells the regular expression engine to match a literal dash character followed by any character (dotsare 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".
为了解释为什么你的模式不起作用,/-./告诉正则表达式引擎匹配一个文字破折号字符后跟任何字符(点是正则表达式中的通配符)。对于“02-25-2010”,每次遇到“-2”时它都会拆分,因为破折号匹配而点匹配“2”。
回答by Jo3y
or just (anything but numbers):
或者只是(除了数字之外的任何东西):
date.split(/\D/);
回答by Allan Ruin
you could just use
你可以用
date.split(/-/);
or
或者
date.split('-');
回答by useless
Then split it on anything but numbers:
然后将其拆分为除数字以外的任何内容:
date.split(/[^0-9]/);
回答by Bobzius
Say your string is:
说你的字符串是:
let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;
You want to split the string by the following delimiters:
您希望通过以下分隔符拆分字符串:
- Colon
- Semicolon
- New line
- 冒号
- 分号
- 新队
You could split the string like this:
您可以像这样拆分字符串:
let rawElements = str.split(new RegExp('[,;\n]', 'g'));
Finally, you may need to trim the elements in the array:
最后,您可能需要修剪数组中的元素:
let elements = rawElements.map(element => element.trim());
回答by Piotr St?pniewski
or just use for date strings 2015-05-20 or 2015.05.20
或仅用于日期字符串 2015-05-20 或 2015.05.20
date.split(/\.|-/);
回答by Omar
try this instead
试试这个
date.split(/\W+/)
date.split(/\W+/)

