假设我们有这些字符串:
1. "a;b;c;d;e"
2. "1;2;3;4;5"
3. "!@#$%^&*()_+;!@#$%^&*()_+;"
有没有办法让调用.split(';')
时它只会在 ;
时 split 是在字母数字字符之间吗?
预期结果:
1. a, b, c, d, e
2. 1, 2, 3, 4, 5
3. !@#$%^&*()_+;!@#$%^&*()_+; // kept as is
这是我到目前为止所拥有的,但它在我“期望”它工作的地方并没有完全正确地分开。
.split(/[A-Za-z0-9];[A-Za-z0-9]/g);
当前结果:
1. (3) ["", ";", ";e"] // no
2. (3) ["", ";", ";5"] // no
3. ["!@#$%^&*()_+;!@#$%^&*()_+;"] // yes
<小时/>
只是为了更新。这不是一个字符串数组。上面的字符串只是示例。还要澄清我期望发生的事情。
分号前面和后面必须是数字或字母。
Yes - both characters beside the ; must be a letter or a number
a;b > a, b
1;2 > 1, 2
c;3 > c, 3
4;d > 4, d
5;6;a; > 5, 6, a
No - when either of the characters beside the ; is not a letter or a number
!;@
12$;525
aa;!$242
bbbbbb;
<小时/>
另一个更新 answer通过 anubhava工作起来就像一个魅力,但我在这个特定的字符串中遇到了一些问题。
TestTEST!@#$%^&*()_+{}|\":?><,./;'[]\\=-this is a long text.test 123455899949949494949499499;TestTEST!@#$%^&*()_+{}|\":?><,./;'[]\\=-this is a long text.test 123455899949949494949499499
他的答案是/([A-Za-z0-9]+);(?=[A-Za-z0-9])/
。但是对上面的字符串使用上述正则表达式将导致
(3)
"TestTEST!@#$%^&*()_+{}|":?><,./;'[]\=-this is a long text.test ",
"123455899949949494949499499",
"TestTEST!@#$%^&*()_+{}|":?><,./;'[]\=-this is a long text.test 123455899949949494949499499"
当预期是
"TestTEST!@#$%^&*()_+{}|\":?><,./;'[]\\=-this is a long text.test 123455899949949494949499499"
"TestTEST!@#$%^&*()_+{}|\":?><,./;'[]\\=-this is a long text.test 123455899949949494949499499"
最佳答案
您可以使用正数和负数lookaheads确保分号前面和后面都是您想要的字符。所以,这会起作用:
let t1 = "a;b;c;d;e";
let t2 = "1;2;3;4;5";
let t3 = "!@#$%^&*()_+;!@#$%^&*()_+;";
console.log(t1.split(/(?![A-Za-z0-9]);(?=[A-Za-z0-9])/g)); // a, b, c, d, e
console.log(t2.split(/(?![A-Za-z0-9]);(?=[A-Za-z0-9])/g)); // 1, 2, 3, 4, 5
console.log(t3.split(/(?![A-Za-z0-9]);(?=[A-Za-z0-9])/g)); // !@#$%^&*()_+;!@#$%^&*()_+;
目前,您的正则表达式匹配一个字母数字字符,后跟一个分号和另一个字母数字字符。
关于javascript - 在字母数字字符之间以分号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48274398/