[英]Split a string based on multiple delimiters
I was trying to split a string based on multiple delimiters by referring How split a string in jquery with multiple strings as separator我试图通过引用How split a string in jquery with multiple strings as separator来根据多个分隔符拆分字符串
Since multiple delimiters I decided to follow由于多个分隔符,我决定遵循
var separators = [' ', '+', '-', '(', ')', '*', '/', ':', '?'];
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
But I'm getting error但我收到错误
Uncaught SyntaxError: Invalid regular expression: / |+|-|(|)|*|/|:|?/: Nothing to repeat
How to solve it?如何解决?
escape needed for regex related characters +,-,(,),*,?正则表达式相关字符 +,-,(,),*,?
var x = "adfds+fsdf-sdf";
var separators = [' ', '\\\+', '-', '\\\(', '\\\)', '\\*', '/', ':', '\\\?'];
console.log(separators.join('|'));
var tokens = x.split(new RegExp(separators.join('|'), 'g'));
console.log(tokens);
This should work:这应该有效:
var separators = [' ', '+', '(', ')', '*', '\\/', ':', '?', '-'];
var tokens = x.split(new RegExp('[' + separators.join('') + ']', 'g'));
Generated regex will be using regex character class: /[ +()*\\/:?-]/g
生成的正则表达式将使用正则表达式字符类: /[ +()*\\/:?-]/g
This way you don't need to escape anything.这样你就不需要逃避任何事情。
The following would be an easier way of accomplishing the same thing.以下将是完成同一件事的更简单的方法。
var tokens = x.split(new RegExp('[-+()*/:? ]', 'g'));
Note that -
must come first (or be escaped), otherwise it will think it is the range
operator (eg az
)请注意-
必须先出现(或被转义),否则它会认为它是range
运算符(例如az
)
我认为您需要转义 +、* 和 ?,因为它们在大多数正则表达式语言中具有特殊含义
This is because characters like +
and *
have special meaning in Regex.这是因为像+
和*
这样的字符在 Regex 中具有特殊含义。
Change your join from |
从|
更改您的加入to |\\
and you should be fine, escaping the literals.到|\\
,你应该没问题,转义文字。
If you want to split based in multiple regexes and dont want to write a big regex You could use replace
and split
.如果您想基于多个正则表达式进行拆分并且不想编写大的正则表达式,您可以使用replace
和split
。 Like this:像这样:
const spliters = [ /(\\[products\\])/g, /(\\[link\\])/g, /(\\[llinks\\])/g, ]; let newString = "aa [products] bb [link] [products] cc [llinks] dd"; spliters.forEach(regex => { newString = newString.replace(regex, match => `æææ${match}æææ`); }); const mySplit = newString.split(/æææ([^æ]+)æææ/) console.log(mySplit);
This works very well for my case.这对我的情况非常有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.