RegexHypertext.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * uGUI-Hypertext (https://github.com/setchi/uGUI-Hypertext)
  3. * Copyright (c) 2019 setchi
  4. * Licensed under MIT (https://github.com/setchi/uGUI-Hypertext/blob/master/LICENSE)
  5. */
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Text.RegularExpressions;
  9. using UnityEngine;
  10. namespace Hypertext
  11. {
  12. public class RegexHypertext : HypertextBase
  13. {
  14. readonly List<Entry> entries = new List<Entry>();
  15. struct Entry
  16. {
  17. public readonly string RegexPattern;
  18. public readonly Color Color;
  19. public readonly Action<string> Callback;
  20. public Entry(string regexPattern, Color color, Action<string> callback)
  21. {
  22. RegexPattern = regexPattern;
  23. Color = color;
  24. Callback = callback;
  25. }
  26. }
  27. /// <summary>
  28. /// 正規表現にマッチした部分文字列にクリックイベントリスナを登録します
  29. /// </summary>
  30. /// <param name="regexPattern">正規表現</param>
  31. /// <param name="onClick">クリック時のコールバック</param>
  32. public void OnClick(string regexPattern, Action<string> onClick)
  33. {
  34. OnClick(regexPattern, color, onClick);
  35. }
  36. /// <summary>
  37. /// 正規表現にマッチした部分文字列に色とクリックイベントリスナを登録します
  38. /// </summary>
  39. /// <param name="regexPattern">正規表現</param>
  40. /// <param name="color">テキストカラー</param>
  41. /// <param name="onClick">クリック時のコールバック</param>
  42. public void OnClick(string regexPattern, Color color, Action<string> onClick)
  43. {
  44. if (string.IsNullOrEmpty(regexPattern) || onClick == null)
  45. {
  46. return;
  47. }
  48. entries.Add(new Entry(regexPattern, color, onClick));
  49. }
  50. public override void RemoveListeners()
  51. {
  52. base.RemoveListeners();
  53. entries.Clear();
  54. }
  55. /// <summary>
  56. /// イベントリスナを追加します
  57. /// テキストの変更などでイベントの再登録が必要なときにも呼び出されます
  58. /// <see cref="HypertextBase.OnClick"/> を使ってクリックイベントリスナを登録してください
  59. /// </summary>
  60. protected override void AddListeners()
  61. {
  62. foreach (var entry in entries)
  63. {
  64. foreach (Match match in Regex.Matches(text, entry.RegexPattern))
  65. {
  66. OnClick(match.Index, match.Value.Length, entry.Color, entry.Callback);
  67. }
  68. }
  69. }
  70. }
  71. }