簡體   English   中英

如何從 Unity 中的字符串中刪除轉義字符(符號或以 \\u 開頭)?

[英]How to remove escape characters (Symbols or start with \u) from string in Unity?

我想從字符串中刪除轉義字符,例如以 \\u 或 \\x 開頭的符號或特殊字符。 這些字符如:\€,\¥,\\x20ac,\\xa5

我的目標:我想從 UserName 中刪除這些字符,並且也不允許用戶在 InputField 中添加這些字符/符號。

您可以使用正則表達式執行此操作。

使用輸入數據的快速示例:

using System;
using System.Text.RegularExpressions;
                
public class Program
{
    public static void Main()
    {
        const string userName = @"MyAwesome\u20acUser\u00a5Name\x20acWith\xa5ForbiddenCharacters";
       
        // Match anything starting with either \u or \x 
        // followed by between 1 and 4 lowercase letters or numbers.
        const string regex = @"\\(u|x)[[a-z\d]{1,4}";
    
        var sanitisedUserName = Regex.Replace(userName, regex, string.Empty);
    
        Console.WriteLine(string.Format("Input User Name: {0}\nSanitised User Name: {1}", userName, sanitisedUserName));

        /* Output:
         * Input User Name: MyAwesome\u20acUser\u00a5Name\x20acWith\xa5ForbiddenCharacters
         * Sanitised User Name: MyAwesomeUserNameWithForbiddenCharacters
         */
    }
}

這是一個 dotnetfiddle,因此您可以看到它正在運行

這是 Regex101 的鏈接,因此您可以了解正則表達式的工作原理

您可以在輸入字段的 OnChanged 事件上運行正則表達式替換函數,或者等待輸入提交后再運行,並將文本設置為替換的結果。

暫無
暫無

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

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