正则表达式(Regex)

作者:追风剑情 发布于:2017-1-9 14:17 分类:C#

示例一:匹配地点坐标


  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. namespace TestXML
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. string text = @"我在这里<桃园村(158,63)>,他在那里<成都(1120,11)>";
  11. string pattern = @"<\S+?\(\d+,\d+\)>";
  12.  
  13. Regex reg_pos = new Regex(pattern);
  14. string modified = reg_pos.Replace(text, "<地名(x,y)>");
  15. Console.WriteLine(modified);
  16.  
  17. MatchCollection mc = Regex.Matches(text, pattern, RegexOptions.Multiline, TimeSpan.FromSeconds(1));
  18. Console.WriteLine("Count=" + mc.Count);
  19. foreach (Match m in mc)
  20. {
  21. Console.WriteLine("Value=" + m.Value);
  22. }
  23. Console.Read();
  24. }
  25. }
  26. }


运行测试

11111.png

示例二:转换坐标格式(这里以转换成NGUI中需要的超链接形式为例)


  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. namespace TestXML
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. string text = @"我在这里<桃园村(158,63)>,他在那里<成都(1120,11)>";
  11. string pattern = @"(<)(\S+?)\(\d+,\d+\)>";
  12.  
  13. MatchCollection mc = Regex.Matches(text, pattern, RegexOptions.Multiline, TimeSpan.FromSeconds(1));
  14. foreach (Match m in mc)
  15. {
  16. ChatPosition pos = new ChatPosition(m.Value);
  17. Console.WriteLine(pos.ToString());
  18. Console.WriteLine(pos.GenerateLink());
  19. }
  20. Console.Read();
  21. }
  22.  
  23. public class ChatPosition
  24. {
  25. private string mText;
  26. private string mName;
  27. private int mX;
  28. private int mZ;
  29.  
  30. public ChatPosition(string text)
  31. {
  32. mText = text;
  33. try
  34. {
  35. mName = text.Substring(1, text.IndexOf('(') - 1);
  36. int startIndex = text.IndexOf('(') + 1;
  37. int endIndex = text.IndexOf(',');
  38. int.TryParse(text.Substring(startIndex, endIndex - startIndex), out mX);
  39.  
  40. startIndex = endIndex + 1;
  41. endIndex = text.IndexOf(')');
  42. int.TryParse(text.Substring(startIndex, endIndex - startIndex), out mZ);
  43. }catch(Exception e){
  44. Console.WriteLine(e.StackTrace);
  45. }
  46. }
  47.  
  48. public int X { get{return mX;} }
  49. public int Z { get { return mZ; } }
  50.  
  51. public string GenerateLink()
  52. {
  53. string link = string.Format(@"[u][link=key_n=pos&id={0}&x={1}&z={2}][F86105]{3}[-][008800]({4},{5})[-][/link][/u]",
  54. 1001, mX, mZ, mName, mX, mZ);
  55. return link;
  56. }
  57.  
  58. public string ToString()
  59. {
  60. return string.Format("Name={0}, X={1}, Z={2}", mName, mX, mZ);
  61. }
  62. }
  63. }
  64. }


运行测试

22222.png

示例三:匹配IP

  1. // 检查IP格式是否合法
  2. public static bool IsValidIP(string ip)
  3. {
  4. string pattern = @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
  5. Regex reg = new Regex(pattern);
  6. return reg.IsMatch(ip);
  7. }

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号