JulianJulianov

01.Regular ExpressionsLab-Match Full Name

Apr 26th, 2020
584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.41 KB | None | 0 0
  1.                                                          Lab: Regular Expressions C#
  2. 01. Match Full Name
  3. Write a C# Program to match full names from a list of names and print them on the console.
  4. Writing the Regular Expression
  5. First, write a regular expression to match a valid full name, according to these conditions:
  6. • A valid full name has the following characteristics:
  7. o   It consists of two words.
  8. o   Each word starts with a capital letter.
  9. o   After the first letter, it only contains lowercase letters afterwards.
  10. o   Each of the two words should be at least two letters long.
  11. o   The two words are separated by a single space.
  12. To help you out, we've outlined several steps:
  13. 1.  Use an online regex tester like https://regex101.com/
  14. 2.  Check out how to use character sets (denoted with square brackets - "[]")
  15. 3.  Specify that you want two words with a space between them (the space character ' ', and not any whitespace symbol)
  16. 4.  For each word, specify that it should begin with an uppercase letter using a character set. The desired characters are in a range – from ‘A’ to ‘Z’.
  17. 5.  For each word, specify that what follows the first letter are only lowercase letters, one or more – use another character set and the correct quantifier.
  18. 6.  To prevent capturing of letters across new lines, put "\b" at the beginning and at the end of your regex. This will ensure that what precedes and what follows the match is a word boundary (like a new line).
  19. In order to check your RegEx, use these values for reference (paste all of them in the Test String field):
  20. Match ALL of these                Match NONE of these
  21. Ivan Ivanov                       ivan ivanov, Ivan ivanov, ivan Ivanov, IVan Ivanov, Ivan IvAnov, Ivan Ivanov, Ivan IvanoV
  22.  
  23. Examples
  24. Input
  25. Ivan Ivanov, Ivan ivanov, ivan Ivanov, IVan Ivanov, Test Testov, Ivan   Ivanov
  26. Output
  27. Ivan Ivanov Test Testov
  28.  
  29. using System;
  30. using System.Text.RegularExpressions;
  31.  
  32. public class Program
  33. {
  34.     public static void Main()
  35.     {
  36.          var names = Console.ReadLine();
  37.  
  38.         var pattern = @"\b[A-Z][a-z]+ [A-Z][a-z]+\b";  //'+' може и да е {1,}, което в този случай, също означава поне една буква и повече!
  39.         var matchedNames = Regex.Matches(names, pattern);
  40.  
  41.         foreach (Match name in matchedNames)
  42.         {
  43.             Console.Write(name.Value + " ");
  44.         }
  45.         Console.WriteLine();
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment