将C#RegEx转换为JavaScript会导致错误无效组

时间:2015-02-24 11:56:07

标签: javascript c# regex

我有以下C#正则表达式:

var r = new Regex(@"
                (?<=[A-Z])(?=[A-Z][a-z]) |
                 (?<=[^A-Z])(?=[A-Z]) |
                 (?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);

r.Replace(PageName, " ")

我正在尝试将其转换为JavaScript:

 var r= new RegExp('(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])');

PageName.split(pageRegex).join(" ")

但它给了我错误:

Uncaught SyntaxError: Invalid regular expression: /(?<=[A-Z])(?=[A-Z][a-z]) | (?<=[^A-Z])(?=[A-Z]) | (?<=[A-Za-z])(?=[^A-Za-z])/: Invalid group

更新:RegEx应转换的一些示例:

  • AllPeople to All People
  • PeopleCRB to People CRB
  • 人与人

1 个答案:

答案 0 :(得分:1)

([A-Z])(?=[A-Z][a-z])|([^A-Z])(?=[A-Z])|([A-Za-z])(?=[^A-Za-z])

Javascript不支持lookbehind:(?<=因此,让一个组看起来后面并替换它。

替换为$1$2$3 。见演示。

https://regex101.com/r/aI4rA5/11

var re = /([A-Z])(?=[A-Z][a-z])|([^A-Z])(?=[A-Z])|([A-Za-z])(?=[^A-Za-z])/gm;
var str = 'AllPeople\nPeopleCRB\nPeople';
var subst = '$1$2$3 ';

var result = str.replace(re, subst);