3

我花了大约三个小时试图了解如何"(?<!^)(?=[A-Z])"根据大写字母在tring处拆分工作,即

string[] s = Regex.Split("TheWorldWithoutStrangers", "(?<!^)(?=[A-Z])");

它是如何工作的 !!我确实理解上述表达式中每个字符的含义,但我不明白它是如何协同工作的。为什么"(? < !^)([A-Z])"不起作用?这意味着每当您发现一个不在换行之后的大写字母时,然后拆分,对吗?


表示一行的^开头,并且(?<!...)是向后看,因此(?<!^)匹配字符串中不在该行开头的任何位置。

该集合[A-Z]匹配任何大写字母,并且(?=...)是积极的向前看,因此(?=[A-Z])匹配字符串中正好在大写字母之前的任何位置。

将它们放在一起,表达式匹配字符串中不在行首的任何位置,即在大写字母之前。

4

2 回答 2

4

The ^ means the beginning of a line, and (?<!...) is a negative look behind, so (?<!^) matches any position in the string that is not right at the beginning of the line.

The set [A-Z] matchies any capital letter, and (?=...) is a positive look ahead, so (?=[A-Z]) matches any position in the string that is right before a capital letter.

Put them together, and the expression matches any position in the string that is not right at the beginning of a line, and that is right before a capital letter.

于 2012-06-03T10:38:29.477 回答
2

这里的关键是这两个部分都是(?<!...)(?=...)宽度的断言。第一个确保^(字符串开头)不会出现在匹配位置之前,第二个确保[A-Z](单个大写字母)出现在匹配位置之后。实际匹配是空的,因为两个断言实际上都不匹配任何字符。整个表达式仅匹配一个位置。

于 2012-06-03T10:44:59.007 回答