簡體   English   中英

RegEx - 擺脫雙重空格?

[英]RegEx — getting rid of double whitespaces?

我有一個應用程序進入,用空白替換“無效”字符(由我的正則表達式定義)。 我想要它,以便如果文件名中有2個或更多空格,則修剪一個。 例如:

在我的應用程序運行后Deal A & B.txt ,將被重命名為Deal A B.txt (3個空格b / w A和B)。 我真正想要的是: Deal A B.txt (A和B之間的一個空格)。

我正在嘗試確定如何執行此操作 - 我想我的應用程序必須至少運行一次所有文件名以替換無效字符,然后再次運行文件名以消除無關的空白。

任何人都可以幫我嗎?
這是我目前用於替換無效字符的代碼:

public partial class CleanNames : Form
{
    public CleanNames()
    {
        InitializeComponent();

    }

    public void Sanitizer(List<string> paths)
    {
        string regPattern = (@"[~#&$!%+{}]+");
        string replacement = " ";

        Regex regExPattern = new Regex(regPattern);


        StreamWriter errors = new StreamWriter(@"S:\Testing\Errors.txt", true);
        var filesCount = new Dictionary<string, int>();


        dataGridView1.Rows.Clear();

           try
            {

              foreach (string files2 in paths)
              {

                string filenameOnly = System.IO.Path.GetFileName(files2);
                string pathOnly = System.IO.Path.GetDirectoryName(files2);
                string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
                string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);


                if (!System.IO.File.Exists(sanitized))
                {
                    DataGridViewRow clean = new DataGridViewRow();
                    clean.CreateCells(dataGridView1);
                    clean.Cells[0].Value = pathOnly;
                    clean.Cells[1].Value = filenameOnly;
                    clean.Cells[2].Value = sanitizedFileName;
                    dataGridView1.Rows.Add(clean);

                    System.IO.File.Move(files2, sanitized);
                }

                else
                {
                    if (filesCount.ContainsKey(sanitized))
                    {
                        filesCount[sanitized]++;
                    }
                    else
                    {
                        filesCount.Add(sanitized, 1);
                    }
                    string newFileName = String.Format("{0}{1}{2}",
                    System.IO.Path.GetFileNameWithoutExtension(sanitized),
                    filesCount[sanitized].ToString(),
                    System.IO.Path.GetExtension(sanitized));
                    string newFilePath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(sanitized), newFileName);
                    System.IO.File.Move(files2, newFilePath);
                    sanitized = newFileName;

                    DataGridViewRow clean = new DataGridViewRow();
                    clean.CreateCells(dataGridView1);
                    clean.Cells[0].Value = pathOnly;
                    clean.Cells[1].Value = filenameOnly;
                    clean.Cells[2].Value = newFileName;

                    dataGridView1.Rows.Add(clean);

                }




              }
            }
           catch (Exception e)
           {
               errors.Write(e);
           }


    }

    private void SanitizeFileNames_Load(object sender, EventArgs e)
    { }

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }


}

問題是,重命名后並非所有文件都具有相同數量的空白。 就像在,我可以得到Deal A&B.txt ,在重命名后將成為Deal A B.txt (1個空格b / w A和B - 這很好)。 但我也會有這樣的文件: Deal A & B & C.txt ,重命名之后是: Deal A B C.txt (A,B和C之間有3個空格 - 不可接受)。

有沒有人有任何想法/代碼如何實現這一目標?

做當地的相當於:

s/\s+/ /g;

只需在regPattern中添加一個空格即可。 任何無效字符和空格的集合都將替換為單個空格。 您可能會浪費一點時間用空格替換空格,但另一方面您不需要第二次字符串操作調用。

這有幫助嗎?

        var regex = new System.Text.RegularExpressions.Regex("\\s{2,}");
        var result = regex.Replace("Some text  with a   lot      of spaces,   and 2\t\ttabs.", " ");
        Console.WriteLine(result);

輸出是:

Some text with a lot of spaces, and 2 tabs.

它只是用一個空格替換2個或更多空格字符的任何序列......


編輯:

為了澄清,我會在你現有的正式版之后立即執行這個正則表達式:

public void Sanitizer(List<string> paths)
{
    string regPattern = (@"[~#&$!%+{}]+");
    string replacement = " ";

    Regex regExPattern = new Regex(regPattern);
    Regex regExPattern2 = new Regex(@"\s{2,}");

和:

          foreach (string files2 in paths)
          {

            string filenameOnly = System.IO.Path.GetFileName(files2);
            string pathOnly = System.IO.Path.GetDirectoryName(files2);
            string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement);
            sanitizedFileName = regExPattern2.Replace(sanitizedFileName, replacement); // clean up whitespace
            string sanitized = System.IO.Path.Combine(pathOnly, sanitizedFileName);

我希望這更有意義。

在您完成消毒之后,只需用1個空格替換2個空格,而字符串中存在2個空格。

while (mystring.Contains("  ")) mystring = mystring.Replace("  "," ");

我認為這是正確的語法......

您可以在第一個正則表達式替換后再執行

@" +" -> " "

正如Fosco所說,格式化:

while (mystring.Contains("  ")) mystring = mystring.Replace("  "," ");

//                        ||                                 ||   |

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM