Javascript 允许您根据正则表达式拆分字符串。是否可以使用此功能仅在分隔符两侧有特定字符时拆分字符串?
例如,如果我想使用 -
字符拆分字符串 12-93
而不是 at-13
?这可能吗?
使用正则表达式似乎很有希望,但是执行 "12-93".split(/[0-9]-[0-9]/)
会产生 ["1", "3"]
因为侧翼数字被认为是定界符的一部分。
我可以在不切断侧翼数字的情况下指定上述拆分模式(破折号前后跟一个数字)吗?
其他例子
"55,966,575-165,162,787"
应该产生 ["55,966,575", "165,162,787"]
"55,966,575x-165,162,787"
应该产生 ["55,966,575x-165,162,787"]
"sdf55,966,575-165,162,787"
应该产生 ["sdf55,966,575", "165,162,787"]
最佳答案
使用两个相邻的字符集似乎可行。
请参阅 https://regex101.com/r/uFHMW1/1 中的示例
([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)
试试这个(住在这里 https://repl.it/EOOQ/0 ):
var strings = [
"55,966,575-165,162,787",
"55,966,575x-165,162,787",
"sdf55,966,575-165,162,787",
];
var pattern = '^([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)$';
var regex = new RegExp(pattern, 'i');
var matched = strings.map(function (string) {
var matches = string.match( regex );
if (matches) {
return [matches[1], matches[2]];
} else {
return [string];
}
});
console.log(matched)
您还可以将上述表达式作为 split()
运行,例如:
string.split(re).filter( str => str.length )
其中 Array.filter()
用于去除当 RegExp 匹配您的输入时创建的前导和尾随空字符串。
var strings = [
"55,966,575-165,162,787",
"55,966,575x-165,162,787",
"sdf55,966,575-165,162,787",
];
var pattern = '^([0-9,a-z]+?[0-9]+)-([0-9]+[0-9,a-z]+)$';
var regex = new RegExp(pattern, 'i');
var matched = strings.map( string => string.split(regex).filter( str => str.length ) );
console.log(matched)
关于javascript - 根据javascript中的侧翼字符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40409429/