1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-13 03:42:57 +08:00

Extract common part of regex to separate method

This commit is contained in:
Bartłomiej Dach 2022-12-03 16:59:43 +01:00
parent 4308120912
commit 7f0d366d01
No known key found for this signature in database

View File

@ -29,7 +29,7 @@ namespace osu.Game.Utils
/// </remarks>
public static string GetNextBestName(IEnumerable<string> existingNames, string desiredName)
{
string pattern = $@"^(?i){Regex.Escape(desiredName)}(?-i)( \((?<copyNumber>[1-9][0-9]*)\))?$";
string pattern = $@"^{getBaselineNameDetectingPattern(desiredName)}$";
var regex = new Regex(pattern, RegexOptions.Compiled);
int bestNumber = findBestNumber(existingNames, regex);
@ -48,7 +48,7 @@ namespace osu.Game.Utils
string name = Path.GetFileNameWithoutExtension(desiredFilename);
string extension = Path.GetExtension(desiredFilename);
string pattern = $@"^(?i){Regex.Escape(name)}(?-i)( \((?<copyNumber>[1-9][0-9]*)\))?(?i){Regex.Escape(extension)}(?-i)$";
string pattern = $@"^{getBaselineNameDetectingPattern(name)}(?i){Regex.Escape(extension)}(?-i)$";
var regex = new Regex(pattern, RegexOptions.Compiled);
int bestNumber = findBestNumber(existingFilenames, regex);
@ -58,6 +58,22 @@ namespace osu.Game.Utils
: $"{name} ({bestNumber.ToString()}){extension}";
}
/// <summary>
/// Generates a basic regex pattern that will match all possible conflicting filenames when picking the best available name, given the <paramref name="desiredName"/>.
/// The generated pattern can be composed into more complicated regexes for particular uses, such as picking filenames, which need additional file extension handling.
/// </summary>
/// <remarks>
/// The regex shall detect:
/// <list type="bullet">
/// <item>all strings that are equal to <paramref name="desiredName"/>,</item>
/// <item>all strings of the format <c>desiredName (number)</c>, where <c>number</c> is a number written using Arabic numerals.</item>
/// </list>
/// All comparisons are made in a case-insensitive manner.
/// If a number is detected in the matches, it will be output to the <c>copyNumber</c> named group.
/// </remarks>
private static string getBaselineNameDetectingPattern(string desiredName)
=> $@"(?i){Regex.Escape(desiredName)}(?-i)( \((?<copyNumber>[1-9][0-9]*)\))?";
private static int findBestNumber(IEnumerable<string> existingNames, Regex regex)
{
var takenNumbers = new HashSet<int>();