regex.gd 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. extends VBoxContainer
  2. var regex = RegEx.new()
  3. func _ready():
  4. %Text.set_text("They asked me \"What's going on \\\"in the manor\\\"?\"")
  5. update_expression(%Expression.text)
  6. func update_expression(text):
  7. regex.compile(text)
  8. update_text()
  9. func update_text():
  10. for child in %List.get_children():
  11. child.queue_free()
  12. if regex.is_valid():
  13. $HBoxContainer.modulate = Color.WHITE
  14. var matches = regex.search_all(%Text.get_text())
  15. if matches.size() >= 1:
  16. # List all matches and their respective captures.
  17. var match_number = 0
  18. for regex_match in matches:
  19. match_number += 1
  20. # `match` is a reserved GDScript keyword.
  21. var match_label = Label.new()
  22. match_label.text = "RegEx match #%d:" % match_number
  23. match_label.modulate = Color(0.6, 0.9, 1.0)
  24. %List.add_child(match_label)
  25. var capture_number = 0
  26. for result in regex_match.get_strings():
  27. capture_number += 1
  28. var capture_label = Label.new()
  29. capture_label.text = " Capture group #%d: %s" % [capture_number, result]
  30. %List.add_child(capture_label)
  31. else:
  32. $HBoxContainer.modulate = Color(1, 0.2, 0.1)
  33. var label = Label.new()
  34. label.text = "Error: Invalid regular expression. Check if the expression is correctly escaped and terminated."
  35. %List.add_child(label)
  36. func _on_help_meta_clicked(_meta):
  37. # Workaround for clickable link doing nothing when clicked.
  38. OS.shell_open("https://regexr.com")