البرمجة

استخدام تعبيرات منتظمة في C# للبحث عن الكلمات التي تبدأ بأرقام أو رموز خاصة

To search for words in a C# list that start with numbers or special characters only, you can use the following regular expression:

csharp
using System; using System.Text.RegularExpressions; using System.Collections.Generic; class Program { static void Main() { List<string> products = new List<string> { "123abc", "!@#def", "ghi456", "jklmno", "789pqr", "$%stu", "vwx987", "yz!@#" }; string pattern = @"^[^a-zA-Z]*[0-9\W]"; Regex regex = new Regex(pattern); foreach (string product in products) { if (regex.IsMatch(product)) { Console.WriteLine(product); } } } }

In this example, the regular expression pattern ^[^a-zA-Z]*[0-9\W] is used:

  • ^ asserts the start of the string.
  • [^a-zA-Z]* matches any character that is not a letter zero or more times.
  • [0-9\W] matches a single digit or any non-word character (special character).

The Regex class is used to compile the regular expression pattern, and IsMatch is used to check if each product in the list matches the pattern. If a match is found, the product is printed to the console.

This code will output the following products:

makefile
123abc !@#def ghi456 789pqr $%stu

These are the products that start with numbers or special characters only.

المزيد من المعلومات

بالطبع! الرمز الذي قدمته يستخدم تعبيرات منتظمة (Regular Expressions) في C# للبحث عن الكلمات التي تبدأ بأرقام أو رموز خاصة فقط في قائمة من الكلمات. هذا الرمز يعتمد على النقاط التالية:

  1. List products = new List: هذا يعني أن لدينا قائمة من السلاسل (strings) تسمى products. يمكن تعديلها لتتناسب مع البيانات الفعلية التي ترغب في استخدامها.

  2. string pattern = @"^[^a-zA-Z]*[0-9\W]": هذا هو النمط لتحديد الكلمات التي تبدأ بأرقام أو رموز خاصة. سنقوم بتحليله بالتفصيل:

    • ^ يعني بداية السلسلة.
    • [^a-zA-Z]* يعني أي حرف غير أبجدي (a-z أو A-Z) يمكن أن يظهر صفر مرة أو أكثر.
    • [0-9\W] يعني حرف رقمي (0-9) متبوعًا برمز غير حرفي (\W)، الذي يشمل الرموز الخاصة.
  3. Regex regex = new Regex(pattern): هنا يتم تجميع النمط إلى كائن Regex لاستخدامه في عمليات البحث.

  4. foreach (string product in products): يتم استخدام حلقة foreach للتحقق من كل منتج في القائمة.

  5. if (regex.IsMatch(product)): يتم استخدام IsMatch للتحقق مما إذا كانت سلسلة المنتج تطابق النمط الذي تم تعريفه.

  6. Console.WriteLine(product): إذا كانت السلسلة تطابق النمط، سيتم طباعتها في الإخراج.

هذا الرمز قابل للتعديل بما يتناسب مع احتياجاتك، مثل تغيير القائمة من الكلمات أو تعديل النمط لمطابقة شروط بحث مختلفة.

زر الذهاب إلى الأعلى