使用包含括号、分号和空格的正则表达式拆分字符串时出现问题

Issue splitting string with RegEx that includes brackets, semicolons and spaces

本文关键字:字符串 拆分 正则表达式 问题 空格 包含括      更新时间:2023-09-26

我在下面有一个字符串:

var sphere1 = CSG.sphere({center: [5, 5, 5], radius: 10, resolution: resolution });<br>
var sphere2 = sphere1.translate([12, 5, 0]);<br>

我尝试使用以下(/,| |[|]|;/作为我的正则表达式进行拆分):

var words = $(selector).html().split(/,| |[|]|;/);

我有三个问题:

  • 我丢失了行尾(BR 标签之前)的分号 - 它们应该在 WORDS 数组中独立拆分

  • 包含括号中第一个数字(5 或 12)的字符串还包括左括号

  • 包含方括号(5 或 0)中最后一个数字的字符串还包括右括号。

基本上,我正在尝试专门"隔离"任何数字,以便我可以单独增加/修改它们。

对正则表达式有什么想法吗?

这可能会给你一个起点

http://jsfiddle.net/JqT4k/1/

var str = "var sphere1 = CSG.sphere({center: [5, 5, 5], radius: 10, resolution: resolution }); var sphere2 = sphere1.translate([12, 5, 0]);";
//evaluates each replace individually
function match_eval(m){
    // m is going to be [5, 5, 5] and then [12, 5, 0], you can do with this as you see fit
    return "[0,0,0]";    
}
alert(str.replace(/'[( *'d+ *,?)+']/g, match_eval));

我在这里修复了它: http://jsfiddle.net/jonnycowboy/w4n3W/12 我使用了在另一个堆栈溢出问题/答案上找到的方法:

'var nums = $(selector).html().match(/[0-9]+/g); var words = $(selector).html().split(/[0-9]+/g); newHtml += '' + words[0] + ''; for (var i = 0; i <nums.length;>