如果字符是大写的话,拆分camelCase str正则表达式?

时间:2018-05-26 17:44:03

标签: c# .net regex

我有这个随机测试随机字符串"... Jc Yikr Cuduxlor B Az I Ngt FT Jtcmvs Hnrzsv Saegaowyta I..."来测试正则表达式"@"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2""拆分camelCase。问题来自FT正则表达式" F T"如何使正则表达式忽略这两个字符串是大写的?

Expected string length 186 but was 185. Strings differ at index 82.
  Expected: "... Jc Yikr Cuduxlor B Az I Ngt F T Jtcmvs Hnrzsv Saegaowyta ..."
  But was:  "... Jc Yikr Cuduxlor B Az I Ngt FT Jtcmvs Hnrzsv Saegaowyta I..."
  --------------------------------------------^

  public static string BreakCamelCase(string str)
  {
   return Regex.Replace( Regex.Replace( str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2" ), @"(\p{Ll})(\P{Ll})", "$1 $2" );
  }

1 个答案:

答案 0 :(得分:1)

使用前瞻怎么样?

只是检查一个大写字符是否跟随它 但实际上没有消耗那个大写字符。

这样,替换字符串只需要1个捕获组。

RegEx Pattern

(\p{L})(?=\p{Lu})

<强> C#

public static string BreakCamelCase(string str)
{
   return Regex.Replace(str, @"(\p{L})(?=\p{Lu})", "$1 ");
}

解释模式

  

(\ p {L}):第一个捕获组($ 1)匹配来自的任何类型的信件   任何语言

     

(?= \ p {Lu}):正向前瞻以检查大写字母   有一个小写的变种