regex.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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"),&RegEx::compile);
  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. return exp.capture_size();
  42. }
  43. String RegEx::get_capture(int capture) const {
  44. ERR_FAIL_COND_V( get_capture_count() <= capture, String() );
  45. return text.substr(captures[capture].start, captures[capture].length);
  46. }
  47. Error RegEx::compile(const String& p_pattern) {
  48. clear();
  49. exp.compile(p_pattern.c_str());
  50. ERR_FAIL_COND_V( !exp.valid(), FAILED );
  51. captures.resize(exp.capture_size());
  52. return OK;
  53. };
  54. int RegEx::find(const String& p_text, int p_start, int p_end) const {
  55. ERR_FAIL_COND_V( !exp.valid(), false );
  56. ERR_FAIL_COND_V( p_text.length() < p_start, false );
  57. ERR_FAIL_COND_V( p_text.length() < p_end, false );
  58. bool res = exp.match(p_text.c_str(), &captures[0], p_start, p_end);
  59. if (res) {
  60. text = p_text;
  61. return captures[0].start;
  62. }
  63. text.clear();
  64. return -1;
  65. };
  66. RegEx::RegEx(const String& p_pattern) {
  67. compile(p_pattern);
  68. };
  69. RegEx::RegEx() {
  70. };
  71. RegEx::~RegEx() {
  72. clear();
  73. };