可能重複:
Regular expression, split string by capital letter but ignore TLA用大寫字母拆分字符串
我有一個字符串,它是幾個單詞的組合,每個字都大寫。
例如:SeveralWordsString
使用C#,我該如何將字符串拆分爲「數字字符串」以智能的方式?
謝謝!
可能重複:
Regular expression, split string by capital letter but ignore TLA用大寫字母拆分字符串
我有一個字符串,它是幾個單詞的組合,每個字都大寫。
例如:SeveralWordsString
使用C#,我該如何將字符串拆分爲「數字字符串」以智能的方式?
謝謝!
使用thi小號正則表達式(我忘了從StackOverflow的答案,我採購它,現在搜索一下):
public static string ToLowercaseNamingConvention(this string s, bool toLowercase)
{
if (toLowercase)
{
var r = new Regex(@"
(?<=[A-Z])(?=[A-Z][a-z]) |
(?<=[^A-Z])(?=[A-Z]) |
(?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
return r.Replace(s, "_").ToLower();
}
else
return s;
}
我用它在這個項目:http://www.ienablemuch.com/2010/12/intelligent-brownfield-mapping-system.html
[編輯]
我發現它現在:How do I convert CamelCase into human-readable names in Java?
精美分裂 「TodayILiveInTheUSAWithSimon」,在 「今天」 前面沒有空間:
using System;
using System.Text.RegularExpressions;
namespace TestSplit
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
var r = new Regex(@"
(?<=[A-Z])(?=[A-Z][a-z]) |
(?<=[^A-Z])(?=[A-Z]) |
(?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
string s = "TodayILiveInTheUSAWithSimon";
Console.WriteLine("YYY{0}ZZZ", r.Replace(s, " "));
}
}
}
輸出:
YYYToday I Live In The USA With SimonZZZ
非常感謝!你能解釋正則表達式的不同部分嗎? – Nir 2010-12-20 12:12:42
您只需通過人物循環,並增加在需要空間:
string theString = "SeveralWordsString";
StringBuilder builder = new StringBuilder();
foreach (char c in theString) {
if (Char.IsUpper(c) && builder.Length > 0) builder.Append(' ');
builder.Append(c);
}
theString = builder.ToString();
string[] SplitCamelCase(string source) {
return Regex.Split(source, @"(?<!^)(?=[A-Z])");
}
樣品:
簡單易用。很好的答案! – MiBol 2017-04-04 17:27:00
很好的答案。使用'return string.Join(「」,Regex.Split(value,@「(?<!^)(?= [AZ](?![AZ] | $))」));'如果你不願意希望大寫縮寫被拆分。 – 2017-05-12 15:39:53
舊線程,但我發現這很有用。這是我從這個答案適應的擴展方法:'公共靜態字符串SplitCamelCase(這個字符串輸入,字符串delimeter =「」) { return input.Any(char.IsUpper)? string.Join(delimeter,Regex.Split(input,「(?<!^)(?= [A-Z])」)):input; }'。這允許您指定分隔符,並且如果輸入字符串不包含任何大寫字母,將返回輸入字符串而不執行RegEx。示例用法:'var s = myString.SplitCamelCase();'或'var s = myString.SplitCamelCase(「,」);' – Anders 2017-08-04 18:47:26
string str1 = "SeveralWordsString";
string newstring = "";
for (int i = 0; i < str1.Length; i++)
{
if (char.IsUpper(str1[i]))
newstring += " ";
newstring += str1[i].ToString();
}
你應該真的使用'StringBuilder'而不是創建大量的字符串。 – Andrew 2017-03-17 03:12:41
public static IEnumerable<string> SplitOnCapitals(string text)
{
Regex regex = new Regex(@"\p{Lu}\p{Ll}*");
foreach (Match match in regex.Matches(text))
{
yield return match.Value;
}
}
這將妥善處理Unicode。
分裂表明你想要一個字符串數組,但它看起來像你想要在字符串中插入空格? – Guffa 2010-12-20 11:00:37