regex.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /*************************************************/
  2. /* regex.cpp */
  3. /*************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /*************************************************/
  7. /* Source code within this file is: */
  8. /* (c) 2007-2010 Juan Linietsky, Ariel Manzur */
  9. /* All Rights Reserved. */
  10. /*************************************************/
  11. #include "regex.h"
  12. #include "nrex.hpp"
  13. #include "core/os/memory.h"
  14. void RegEx::_bind_methods() {
  15. ObjectTypeDB::bind_method(_MD("compile","pattern", "expanded"),&RegEx::compile, DEFVAL(true));
  16. ObjectTypeDB::bind_method(_MD("find","text","start","end"),&RegEx::find, DEFVAL(0), DEFVAL(-1));
  17. ObjectTypeDB::bind_method(_MD("clear"),&RegEx::clear);
  18. ObjectTypeDB::bind_method(_MD("is_valid"),&RegEx::is_valid);
  19. ObjectTypeDB::bind_method(_MD("get_capture_count"),&RegEx::get_capture_count);
  20. ObjectTypeDB::bind_method(_MD("get_capture","capture"),&RegEx::get_capture);
  21. ObjectTypeDB::bind_method(_MD("get_captures"),&RegEx::_bind_get_captures);
  22. };
  23. StringArray RegEx::_bind_get_captures() const {
  24. StringArray ret;
  25. int count = get_capture_count();
  26. for (int i=0; i<count; i++) {
  27. String c = get_capture(i);
  28. ret.push_back(c);
  29. };
  30. return ret;
  31. };
  32. void RegEx::clear() {
  33. text.clear();
  34. captures.clear();
  35. exp.reset();
  36. };
  37. bool RegEx::is_valid() const {
  38. return exp.valid();
  39. };
  40. int RegEx::get_capture_count() const {
  41. ERR_FAIL_COND_V( !exp.valid(), 0 );
  42. return exp.capture_size();
  43. }
  44. String RegEx::get_capture(int capture) const {
  45. ERR_FAIL_COND_V( get_capture_count() <= capture, String() );
  46. return text.substr(captures[capture].start, captures[capture].length);
  47. }
  48. Error RegEx::compile(const String& p_pattern, bool expanded) {
  49. clear();
  50. exp.compile(p_pattern.c_str(), expanded);
  51. ERR_FAIL_COND_V( !exp.valid(), FAILED );
  52. captures.resize(exp.capture_size());
  53. return OK;
  54. };
  55. int RegEx::find(const String& p_text, int p_start, int p_end) const {
  56. ERR_FAIL_COND_V( !exp.valid(), -1 );
  57. ERR_FAIL_COND_V( p_text.length() < p_start, -1 );
  58. ERR_FAIL_COND_V( p_text.length() < p_end, -1 );
  59. bool res = exp.match(p_text.c_str(), &captures[0], p_start, p_end);
  60. if (res) {
  61. text = p_text;
  62. return captures[0].start;
  63. }
  64. text.clear();
  65. return -1;
  66. };
  67. RegEx::RegEx(const String& p_pattern) {
  68. compile(p_pattern);
  69. };
  70. RegEx::RegEx() {
  71. };
  72. RegEx::~RegEx() {
  73. clear();
  74. };