最近沉迷于把js改写为c#的项目(甲方要求,要我说改p啊改)。写得差不多了,但是在改的时候,在正则表达式上遇到了一点点坑,这里记录一下。两种语言下正则表达式的编写不在本文阐述范围内。
参考:
https://www.runoob.com/csharp/csharp-regular-expressions.html
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp
实例
re是正则表达式
改写前(js)
var matchArray;
var matchStrs;
while (matchArray = re.exec(sequence)) {
matchPosition = re.lastIndex;
matchStrs.push(matchArray[0]);
re.lastIndex = re.lastIndex - RegExp.lastMatch.length + 1;
}
改写后(c#)
Regex regex1 = new Regex(re);
Match match1 = regex1.Match(sequence);
List<string> matchStrs = new List<string>();
while (match1.Success) {
matchPosition = match1.Index + match1.Length;
matchStrs.Add(match1.ToString());
match1 = regex1.Match(sequence, match1.Index + 1);
}
解释
- js的lastIndex是一个可读写的int属性,用来指定下一次匹配从什么位置开始
只有正则表达式使用g、y时才起作用。它需要满足以下规则:
- 如果lastIndex大于字符串长度或者从lastIndex起匹配全部失败,lastIndex会被设为0
- 如果匹配成功,lastIndex会被设置为紧跟最近一次成功匹配的下一个位置。举例:
var re = /(hi)?/g;
console.log(re.exec("hi")); // Array ["hi", "hi"]
console.log(re.lastIndex); // 2
- c#的match类的Index则是匹配处的开头,举例:
Regex regex1 = new Regex("ag");
string sequence = "cgagaag";
Match match1 = regex1.Match(sequence);
while(match1.Success){
Console.WriteLine(match1.Index); // 输出 2,5
match1 = regex1.Match(sequence, match1.Index+1);
}
- js的RegExp.lastMatch就是上一次匹配的子串