如何使用正则表达式拆分字母和数字上的字符串和数字后跟数字

时间:2021-09-20 18:36:46

So I was wondering how I would go about splitting a String on specific characters/conditions using Regular Expressions like the following:

所以我想知道如何使用正则表达式在特定字符/条件上拆分字符串,如下所示:

  • On digits
  • On Letters
  • On digits following a caret
  • 在插入符号后的数字上

Here could be an example:

这可能是一个例子:

var str1 = "62y^2";

Would return as an array:

将作为数组返回:

[62,y,^2]


Thanks for the help.

谢谢您的帮助。

3 个解决方案

#1


2  

You can use String.match() instead of split with the following regular expression (Regex101):

您可以使用String.match()而不是使用以下正则表达式(Regex101)进行拆分:

var str="62y^2ad23^123";

var result = str.match(/\^?\d+|[a-z]+/gi);

console.log(result);

#2


1  

You may try the following approach:

您可以尝试以下方法:

var str="62y^2ad23^123";

console.log(str.split(/(\^\d+|[a-zA-Z]+|\d+)/).filter(function(n){ return n != "" }));

#3


0  

Try the below regex

试试下面的正则表达式

var str = "62y^2";
str.match(/\^(\d+|[a-zA-Z]+)|[a-zA-Z]+|\d+/g); // ["62", "y", "^2"]

#1


2  

You can use String.match() instead of split with the following regular expression (Regex101):

您可以使用String.match()而不是使用以下正则表达式(Regex101)进行拆分:

var str="62y^2ad23^123";

var result = str.match(/\^?\d+|[a-z]+/gi);

console.log(result);

#2


1  

You may try the following approach:

您可以尝试以下方法:

var str="62y^2ad23^123";

console.log(str.split(/(\^\d+|[a-zA-Z]+|\d+)/).filter(function(n){ return n != "" }));

#3


0  

Try the below regex

试试下面的正则表达式

var str = "62y^2";
str.match(/\^(\d+|[a-zA-Z]+)|[a-zA-Z]+|\d+/g); // ["62", "y", "^2"]