簡體   English   中英

如何使用正則表達式從輸入字符串中提取所有非字母數字字符?

[英]How can I extract all non-alphanumeric characters from an input string using Regular Expressions?

目標:獲取所有非字母數字字符,即使它們不是連續的。
設置:我在ASP.Net頁面上有一個文本框,在TextChanged上調用C#代碼隱藏方法。 此事件處理程序針對Regex模式運行文本框輸入。
問題:我無法創建正確的正則表達式模式來提取所有非字母數字字符。

這是字符串輸入: string titleString = @"%2@#$%^&";

這些是我嘗試的C#Regex模式:

string titlePattern = @"(\\b[^A-Za-z0-9]+)"; 結果用@#$%^& (注意:如果我使用這個輸入字符串%2@35%^& ,那么上面的正則表達式模式將識別@符號,然后是%^& ),但絕不是前導%符號)。
string titlePattern = @"(\\A[^A-Za-z0-9]+)"; 結果與%
string titlePattern = @"(\\b\\W[^A-Za-z0-9]+)"; @#$%^&

附注:我也在帶有foreach循環的MS Visual Studio控制台應用程序中運行它,以便將所有無效字符放入集合中,並且還使用網站測試輸入和模式: http//regexstorm.net /測試儀

將replace方法與您的選擇字符串一起使用。

編輯:仔細閱讀后,我看到你想要相反的字符串。 這兩個都是。

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string Source = @"H)*e/.?l\l{}*o ][W!~`@#""or^-_=+ld!";
            string Trash = @"[^a-zA-Z0-9]";
            string InvertedTrash = @"[a-zA-Z0-9]";

            Output(Source, Trash);
            Console.WriteLine($"{System.Environment.NewLine}Opposite Day!{System.Environment.NewLine}");
            Output(Source, InvertedTrash);
            Console.ReadKey();
        }
        static string TakeOutTheTrash(string Source, string Trash)
        {
            return (new Regex(Trash)).Replace(Source, string.Empty);
        }
        static void Output(string Source, string Trash)
        {
            string Sanitized = TakeOutTheTrash(Source, Trash);
            Console.WriteLine($"Started with: {Source}");
            Console.WriteLine($"Ended with: {Sanitized}");
        }
    }
}

暫無
暫無

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

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