この文字列から移動するにはどうすればよいですか: "ThisIsMyCapsDelimitedString"
...この文字列へ:「これは私のキャップで区切られた文字列です」
VB.netのコードの最少行が推奨されますが、C#も歓迎します。
乾杯!
この文字列から移動するにはどうすればよいですか: "ThisIsMyCapsDelimitedString"
...この文字列へ:「これは私のキャップで区切られた文字列です」
VB.netのコードの最少行が推奨されますが、C#も歓迎します。
乾杯!
私はこれを少し前に作りました。キャメルケース名の各コンポーネントに一致します。
/([A-Z]+(?=$|[A-Z][a-z])|[A-Z]?[a-z]+)/g
例えば:
"SimpleHTTPServer" => ["Simple", "HTTP", "Server"]
"camelCase" => ["camel", "Case"]
それを変換して、単語の間にスペースを挿入するだけです:
Regex.Replace(s, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ")
数字を処理する必要がある場合:
/([A-Z]+(?=$|[A-Z][a-z]|[0-9])|[A-Z]?[a-z]+|[0-9]+)/g
Regex.Replace(s,"([a-z](?=[A-Z]|[0-9])|[A-Z](?=[A-Z][a-z]|[0-9])|[0-9](?=[^0-9]))","$1 ")
Regex.Replace("ThisIsMyCapsDelimitedString", "(\\B[A-Z])", " $1")
素晴らしい答え、MizardX! 「AddressLine1」が「Address Line1」ではなく「Address Line 1」になるように、数字を個別の単語として扱うように少し調整しました。
Regex.Replace(s, "([a-z](?=[A-Z0-9])|[A-Z](?=[A-Z][a-z]))", "$1 ")
ほんの少しの変化のために...正規表現を使用しない拡張メソッドを次に示します。
public static class CamelSpaceExtensions
{
public static string SpaceCamelCase(this String input)
{
return new string(Enumerable.Concat(
input.Take(1), // No space before initial cap
InsertSpacesBeforeCaps(input.Skip(1))
).ToArray());
}
private static IEnumerable<char> InsertSpacesBeforeCaps(IEnumerable<char> input)
{
foreach (char c in input)
{
if (char.IsUpper(c))
{
yield return ' ';
}
yield return c;
}
}
}
Grant Wagner の優れたコメントはさておき:
Dim s As String = RegularExpressions.Regex.Replace("ThisIsMyCapsDelimitedString", "([A-Z])", " $1")
頭字語と数字をサポートするソリューションが必要でした。この正規表現ベースのソリューションは、次のパターンを個々の「単語」として扱います。
ワンライナーとしてそれを行うことができます:
Regex.Replace(value, @"(?<!^)((?<!\d)\d|(?(?<=[A-Z])[A-Z](?=[a-z])|[A-Z]))", " $1")
より読みやすいアプローチの方が良いかもしれません:
using System.Text.RegularExpressions;
namespace Demo
{
public class IntercappedStringHelper
{
private static readonly Regex SeparatorRegex;
static IntercappedStringHelper()
{
const string pattern = @"
(?<!^) # Not start
(
# Digit, not preceded by another digit
(?<!\d)\d
|
# Upper-case letter, followed by lower-case letter if
# preceded by another upper-case letter, e.g. 'G' in HTMLGuide
(?(?<=[A-Z])[A-Z](?=[a-z])|[A-Z])
)";
var options = RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled;
SeparatorRegex = new Regex(pattern, options);
}
public static string SeparateWords(string value, string separator = " ")
{
return SeparatorRegex.Replace(value, separator + "$1");
}
}
}
(XUnit)テストからの抜粋は次のとおりです。
[Theory]
[InlineData("PurchaseOrders", "Purchase-Orders")]
[InlineData("purchaseOrders", "purchase-Orders")]
[InlineData("2Unlimited", "2-Unlimited")]
[InlineData("The2Unlimited", "The-2-Unlimited")]
[InlineData("Unlimited2", "Unlimited-2")]
[InlineData("222Unlimited", "222-Unlimited")]
[InlineData("The222Unlimited", "The-222-Unlimited")]
[InlineData("Unlimited222", "Unlimited-222")]
[InlineData("ATeam", "A-Team")]
[InlineData("TheATeam", "The-A-Team")]
[InlineData("TeamA", "Team-A")]
[InlineData("HTMLGuide", "HTML-Guide")]
[InlineData("TheHTMLGuide", "The-HTML-Guide")]
[InlineData("TheGuideToHTML", "The-Guide-To-HTML")]
[InlineData("HTMLGuide5", "HTML-Guide-5")]
[InlineData("TheHTML5Guide", "The-HTML-5-Guide")]
[InlineData("TheGuideToHTML5", "The-Guide-To-HTML-5")]
[InlineData("TheUKAllStars", "The-UK-All-Stars")]
[InlineData("AllStarsUK", "All-Stars-UK")]
[InlineData("UKAllStars", "UK-All-Stars")]
多様性を高めるために、単純な古い C# オブジェクトを使用すると、次のように @MizardX の優れた正規表現と同じ出力が生成されます。
public string FromCamelCase(string camel)
{ // omitted checking camel for null
StringBuilder sb = new StringBuilder();
int upperCaseRun = 0;
foreach (char c in camel)
{ // append a space only if we're not at the start
// and we're not already in an all caps string.
if (char.IsUpper(c))
{
if (upperCaseRun == 0 && sb.Length != 0)
{
sb.Append(' ');
}
upperCaseRun++;
}
else if( char.IsLower(c) )
{
if (upperCaseRun > 1) //The first new word will also be capitalized.
{
sb.Insert(sb.Length - 1, ' ');
}
upperCaseRun = 0;
}
else
{
upperCaseRun = 0;
}
sb.Append(c);
}
return sb.ToString();
}
以下は、以下を Title Case に変換するプロトタイプです。
明らかに、「ToTitleCase」メソッドだけが必要です。
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var examples = new List<string> {
"THEQuickBrownFox",
"theQUICKBrownFox",
"TheQuickBrownFOX",
"TheQuickBrownFox",
"the_quick_brown_fox",
"theFOX",
"FOX",
"QUICK"
};
foreach (var example in examples)
{
Console.WriteLine(ToTitleCase(example));
}
}
private static string ToTitleCase(string example)
{
var fromSnakeCase = example.Replace("_", " ");
var lowerToUpper = Regex.Replace(fromSnakeCase, @"(\p{Ll})(\p{Lu})", "$1 $2");
var sentenceCase = Regex.Replace(lowerToUpper, @"(\p{Lu}+)(\p{Lu}\p{Ll})", "$1 $2");
return new CultureInfo("en-US", false).TextInfo.ToTitleCase(sentenceCase);
}
}
コンソール出力は次のようになります。
THE Quick Brown Fox The QUICK Brown Fox The Quick Brown FOX The Quick Brown Fox The Quick Brown Fox The FOX FOX QUICK
string s = "ThisIsMyCapsDelimitedString";
string t = Regex.Replace(s, "([A-Z])", " $1").Substring(1);
素朴な正規表現ソリューション。O'Conner を処理せず、文字列の先頭にもスペースを追加します。
s = "ThisIsMyCapsDelimitedString"
split = Regex.Replace(s, "[A-Z0-9]", " $&");
おそらくもっとエレガントな解決策がありますが、これは私が頭の中で思いついたものです:
string myString = "ThisIsMyCapsDelimitedString";
for (int i = 1; i < myString.Length; i++)
{
if (myString[i].ToString().ToUpper() == myString[i].ToString())
{
myString = myString.Insert(i, " ");
i++;
}
}