如何使用正则表达式将字符串拆分为{}

时间:2016-04-14 06:55:09

标签: javascript regex

var ap = angular.module('myApp', ['trNgGrid', 'ngRoute']);

//controller 1
ap.controller("MainCtrl", function ($scope, $http) {
    $scope.model = {};

......
....

$scope.isAjaxInProgress = true;
$scope.errorMessage = undefined;

$http.post("/ModuleMst/GridData", $scope.requestedItemsGridOptions)
.then(function (data) {
    $scope.model.itemList = data.items;
    $scope.model.totalCount = data.TotalCount;
}
,function () {
    $scope.errorMessage = "An Error has occured while loading data!";
});

})
.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {

    $routeProvider.when('/ModuleMst', {
        templateUrl: '/Setup/ModuleMst/GridData'
        //controller: 'ModuleMst',
    });
    $routeProvider.otherwise({
        redirectTo: '/'
    });

    $locationProvider.html5Mode(false).hashPrefix('!');

}]);

如何使用正则表达式拆分此字符串并将结果保存在类似

的数组中
$http.post()

5 个答案:

答案 0 :(得分:2)

或者只是简单地使用前瞻:

var arr = string.split(/(?=\{)/);



var string = '{user: Jack}{user: Dave}{user: John}{user: Hou}';

document.write(string.split(/(?=\{)/));




此致

答案 1 :(得分:1)

如果它只是对某些字符串(而不是JSON)的测试,请使用以下正则表达式:

var string = '{user: Jack}{user: Dave}{user: John}{user: Hou}',
    re = /\{\w+?:\s?\w+?\}/g;

console.log(string.match(re));
// ["{user: Jack}", "{user: Dave}", "{user: John}", "{user: Hou}"]

答案 2 :(得分:1)

如果{}内没有嵌套{},请尝试

var string = '{user: Jack}{user: Dave}{user: John}{user: Hou}';

var output = string.split("}{").map(function(val, index, arr) {
  if (index == 0 ) 
  {
    if ( arr.length > 0 )
    {
      val += "}";
    }
  } 
  else if (index == arr.length - 1) 
  {
    val = "{" + val;
  } 
  else 
  {
    val = "{" + val + "}";
  }
  return val;
});

document.body.innerHTML += JSON.stringify(output, 0, 4);

答案 3 :(得分:1)

拆分此regex

(?=(?!^){)

JS代码



var string = '{user: Jack}{user: Dave}{user: John}{user: Hou}';

document.write(string.split(/(?=(?!^){)/));




<强> Ideone Demo

答案 4 :(得分:1)

您可以将该表达式用作String.prototype.match() method

的参数
$(function(){
   $('input[name="btnicon"]').click(function(){
      $('#tabicon').show();
      $('#tabimages').hide();
   });
   $('input[name="btnimages"]').click(function(){
      $('#tabicon').hide();
      $('#tabimages').show();
   });
 });

这会产生类似的结果:

\{(.*?)\}

它会为你提供一个你想要的数组。 如果你必须经常使用正则表达式,你可以使用这个很酷的正则表达式测试器:https://regex101.com/