javascript - 正则表达式分割字符串的问题

WBOY
Release: 2016-06-06 20:15:04
Original
1275 people have browsed it

我想对字符串“1,2,,,'3,4',5”,实现分割结果为['1','2',‘’,‘’,‘3,4’,'5']
请教正则表达式该怎么写

============================================================
我自己用正则实现的,php代码:

<code>var_dump(preg_split("/[,]?'([^']+)'[,]?|[,]+?/", "1,2,6,7,,'3,4',5,8,9", 0, PREG_SPLIT_DELIM_CAPTURE));</code>
Copy after login
Copy after login

结果:

<code>array(9) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "6"
  [3]=>
  string(1) "7"
  [4]=>
  string(0) ""
  [5]=>
  string(3) "3,4"
  [6]=>
  string(1) "5"
  [7]=>
  string(1) "8"
  [8]=>
  string(1) "9"
}</code>
Copy after login
Copy after login

不知道这样是否有问题

回复内容:

我想对字符串“1,2,,,'3,4',5”,实现分割结果为['1','2',‘’,‘’,‘3,4’,'5']
请教正则表达式该怎么写

============================================================
我自己用正则实现的,php代码:

<code>var_dump(preg_split("/[,]?'([^']+)'[,]?|[,]+?/", "1,2,6,7,,'3,4',5,8,9", 0, PREG_SPLIT_DELIM_CAPTURE));</code>
Copy after login
Copy after login

结果:

<code>array(9) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "6"
  [3]=>
  string(1) "7"
  [4]=>
  string(0) ""
  [5]=>
  string(3) "3,4"
  [6]=>
  string(1) "5"
  [7]=>
  string(1) "8"
  [8]=>
  string(1) "9"
}</code>
Copy after login
Copy after login

不知道这样是否有问题

不会用正则,但这个问题可以用split()

<code>var str = "1,2,,,'3,4',5";
str.split(",");</code>
Copy after login

<code><?php $str = "'1','2','3','4','5','6','','','3,4','2333'";
    $result = preg_split("/',/", $str);

    for ($i = count($result) - 1; $i >= 0; $i--) {
        $result[$i] = trim($result[$i], "'");
    }

    var_dump($result);
</code>
Copy after login

结果:

<code>array(10) { 
    [0]=> string(1) "1" 
    [1]=> string(1) "2" 
    [2]=> string(1) "3" 
    [3]=> string(1) "4" 
    [4]=> string(1) "5" 
    [5]=> string(1) "6" 
    [6]=> string(0) "" 
    [7]=> string(0) ""
    [8]=> string(0) "3,4"
    [9]=> string(4) "2333" 
}
</code>
Copy after login

暂时想到是这样,能简化再修改。

(并不是最简答。

提供一个思路:

<code class="js">var str = "1,2,,,'3,4',5";

// 这里先利用正则将字符串 '3,4' 中的 `,` 先换成其他字符,如 `*`,然后再做 `split` 最后再检查每个元素里的 `*`,将它换回来
var temp = str.replace(/'(\w)+,(\w)+'/, '$1*$2').split(','); 

str = temp.map(function(n){
  return n.replace(/\*/, ',');
});</code>
Copy after login

希望有所帮助~ :)

('.*')|[^,]
这样,试试!
图片描述

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template