1 /**
2 Class for searching text for patterns using regular expressions.
3 
4 Copyright:
5 Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur.  
6 Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md)  
7 Copyright (c) 2017-2018 Godot-D contributors  
8 
9 License: $(LINK2 https://opensource.org/licenses/MIT, MIT License)
10 
11 
12 */
13 module godot.regex;
14 import std.meta : AliasSeq, staticIndexOf;
15 import std.traits : Unqual;
16 import godot.d.traits;
17 import godot.core;
18 import godot.c;
19 import godot.d.bind;
20 import godot.d.reference;
21 import godot.globalenums;
22 import godot.object;
23 import godot.classdb;
24 import godot.reference;
25 import godot.regexmatch;
26 /**
27 Class for searching text for patterns using regular expressions.
28 
29 A regular expression (or regex) is a compact language that can be used to recognise strings that follow a specific pattern, such as URLs, email addresses, complete sentences, etc. For instance, a regex of `ab$(D 0-9)` would find any string that is `ab` followed by any number from `0` to `9`. For a more in-depth look, you can easily find various tutorials and detailed explanations on the Internet.
30 To begin, the RegEx object needs to be compiled with the search pattern using $(D compile) before it can be used.
31 
32 
33 var regex = RegEx.new()
34 regex.compile("\\w-(\\d+)")
35 
36 
37 The search pattern must be escaped first for GDScript before it is escaped for the expression. For example, `compile("\\d+")` would be read by RegEx as `\d+`. Similarly, `compile("\"(?:\\\\.|$(D ^\"))*\"")` would be read as `"(?:\\.|$(D ^"))*"`.
38 Using $(D search), you can find the pattern within the given text. If a pattern is found, $(D RegExMatch) is returned and you can retrieve details of the results using methods such as $(D RegExMatch.getString) and $(D RegExMatch.getStart).
39 
40 
41 var regex = RegEx.new()
42 regex.compile("\\w-(\\d+)")
43 var result = regex.search("abc n-0123")
44 if result:
45     print(result.get_string()) # Would print n-0123
46 
47 
48 The results of capturing groups `()` can be retrieved by passing the group number to the various methods in $(D RegExMatch). Group 0 is the default and will always refer to the entire pattern. In the above example, calling `result.get_string(1)` would give you `0123`.
49 This version of RegEx also supports named capturing groups, and the names can be used to retrieve the results. If two or more groups have the same name, the name would only refer to the first one with a match.
50 
51 
52 var regex = RegEx.new()
53 regex.compile("d(?<digit>$(D 0-9)+)|x(?<digit>$(D 0-9a-f)+)")
54 var result = regex.search("the number is x2f")
55 if result:
56     print(result.get_string("digit")) # Would print 2f
57 
58 
59 If you need to process multiple results, $(D searchAll) generates a list of all non-overlapping results. This can be combined with a `for` loop for convenience.
60 
61 
62 for result in regex.search_all("d01, d03, d0c, x3f and x42"):
63     print(result.get_string("digit"))
64 # Would print 01 03 0 3f 42
65 
66 
67 $(B Example of splitting a string using a RegEx:)
68 
69 
70 var regex = RegEx.new()
71 regex.compile("\\S+") # Negated whitespace character class.
72 var results = []
73 for result in regex.search_all("One  Two \n\tThree"):
74     results.push_back(result.get_string())
75 # The `results` array now contains "One", "Two", "Three".
76 
77 
78 $(B Note:) Godot's regex implementation is based on the $(D url=https://www.pcre.org/)PCRE2$(D /url) library. You can view the full pattern reference $(D url=https://www.pcre.org/current/doc/html/pcre2pattern.html)here$(D /url).
79 $(B Tip:) You can use $(D url=https://regexr.com/)Regexr$(D /url) to test regular expressions online.
80 */
81 @GodotBaseClass struct RegEx
82 {
83 	package(godot) enum string _GODOT_internal_name = "RegEx";
84 public:
85 @nogc nothrow:
86 	union { /** */ godot_object _godot_object; /** */ Reference _GODOT_base; }
87 	alias _GODOT_base this;
88 	alias BaseClasses = AliasSeq!(typeof(_GODOT_base), typeof(_GODOT_base).BaseClasses);
89 	package(godot) __gshared bool _classBindingInitialized = false;
90 	package(godot) static struct GDNativeClassBinding
91 	{
92 		__gshared:
93 		@GodotName("clear") GodotMethod!(void) clear;
94 		@GodotName("compile") GodotMethod!(GodotError, String) compile;
95 		@GodotName("get_group_count") GodotMethod!(long) getGroupCount;
96 		@GodotName("get_names") GodotMethod!(Array) getNames;
97 		@GodotName("get_pattern") GodotMethod!(String) getPattern;
98 		@GodotName("is_valid") GodotMethod!(bool) isValid;
99 		@GodotName("search") GodotMethod!(RegExMatch, String, long, long) search;
100 		@GodotName("search_all") GodotMethod!(Array, String, long, long) searchAll;
101 		@GodotName("sub") GodotMethod!(String, String, String, bool, long, long) sub;
102 	}
103 	/// 
104 	pragma(inline, true) bool opEquals(in RegEx other) const
105 	{ return _godot_object.ptr is other._godot_object.ptr; }
106 	/// 
107 	pragma(inline, true) typeof(null) opAssign(typeof(null) n)
108 	{ _godot_object.ptr = n; return null; }
109 	/// 
110 	pragma(inline, true) bool opEquals(typeof(null) n) const
111 	{ return _godot_object.ptr is n; }
112 	/// 
113 	size_t toHash() const @trusted { return cast(size_t)_godot_object.ptr; }
114 	mixin baseCasts;
115 	/// Construct a new instance of RegEx.
116 	/// Note: use `memnew!RegEx` instead.
117 	static RegEx _new()
118 	{
119 		static godot_class_constructor constructor;
120 		if(constructor is null) constructor = _godot_api.godot_get_class_constructor("RegEx");
121 		if(constructor is null) return typeof(this).init;
122 		return cast(RegEx)(constructor());
123 	}
124 	@disable new(size_t s);
125 	/**
126 	This method resets the state of the object, as if it was freshly created. Namely, it unassigns the regular expression of this object.
127 	*/
128 	void clear()
129 	{
130 		checkClassBinding!(typeof(this))();
131 		ptrcall!(void)(GDNativeClassBinding.clear, _godot_object);
132 	}
133 	/**
134 	Compiles and assign the search pattern to use. Returns $(D constant OK) if the compilation is successful. If an error is encountered, details are printed to standard output and an error is returned.
135 	*/
136 	GodotError compile(in String pattern)
137 	{
138 		checkClassBinding!(typeof(this))();
139 		return ptrcall!(GodotError)(GDNativeClassBinding.compile, _godot_object, pattern);
140 	}
141 	/**
142 	Returns the number of capturing groups in compiled pattern.
143 	*/
144 	long getGroupCount() const
145 	{
146 		checkClassBinding!(typeof(this))();
147 		return ptrcall!(long)(GDNativeClassBinding.getGroupCount, _godot_object);
148 	}
149 	/**
150 	Returns an array of names of named capturing groups in the compiled pattern. They are ordered by appearance.
151 	*/
152 	Array getNames() const
153 	{
154 		checkClassBinding!(typeof(this))();
155 		return ptrcall!(Array)(GDNativeClassBinding.getNames, _godot_object);
156 	}
157 	/**
158 	Returns the original search pattern that was compiled.
159 	*/
160 	String getPattern() const
161 	{
162 		checkClassBinding!(typeof(this))();
163 		return ptrcall!(String)(GDNativeClassBinding.getPattern, _godot_object);
164 	}
165 	/**
166 	Returns whether this object has a valid search pattern assigned.
167 	*/
168 	bool isValid() const
169 	{
170 		checkClassBinding!(typeof(this))();
171 		return ptrcall!(bool)(GDNativeClassBinding.isValid, _godot_object);
172 	}
173 	/**
174 	Searches the text for the compiled pattern. Returns a $(D RegExMatch) container of the first matching result if found, otherwise `null`. The region to search within can be specified without modifying where the start and end anchor would be.
175 	*/
176 	Ref!RegExMatch search(in String subject, in long offset = 0, in long end = -1) const
177 	{
178 		checkClassBinding!(typeof(this))();
179 		return ptrcall!(RegExMatch)(GDNativeClassBinding.search, _godot_object, subject, offset, end);
180 	}
181 	/**
182 	Searches the text for the compiled pattern. Returns an array of $(D RegExMatch) containers for each non-overlapping result. If no results were found, an empty array is returned instead. The region to search within can be specified without modifying where the start and end anchor would be.
183 	*/
184 	Array searchAll(in String subject, in long offset = 0, in long end = -1) const
185 	{
186 		checkClassBinding!(typeof(this))();
187 		return ptrcall!(Array)(GDNativeClassBinding.searchAll, _godot_object, subject, offset, end);
188 	}
189 	/**
190 	Searches the text for the compiled pattern and replaces it with the specified string. Escapes and backreferences such as `$1` and `$name` are expanded and resolved. By default, only the first instance is replaced, but it can be changed for all instances (global replacement). The region to search within can be specified without modifying where the start and end anchor would be.
191 	*/
192 	String sub(in String subject, in String replacement, in bool all = false, in long offset = 0, in long end = -1) const
193 	{
194 		checkClassBinding!(typeof(this))();
195 		return ptrcall!(String)(GDNativeClassBinding.sub, _godot_object, subject, replacement, all, offset, end);
196 	}
197 }