PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/std/regex/package.d

https://github.com/adamsaka/phobos
D | 1429 lines | 672 code | 103 blank | 654 comment | 157 complexity | 9ca8e90ac8ea140251c41d333511b7bb MD5 | raw file
  1. /++
  2. $(SECTION Intro)
  3. $(LUCKY Regular expressions) are a commonly used method of pattern matching
  4. on strings, with $(I regex) being a catchy word for a pattern in this domain
  5. specific language. Typical problems usually solved by regular expressions
  6. include validation of user input and the ubiquitous find & replace
  7. in text processing utilities.
  8. $(SECTION Synopsis)
  9. ---
  10. import std.regex;
  11. import std.stdio;
  12. void main()
  13. {
  14. // Print out all possible dd/mm/yy(yy) dates found in user input.
  15. auto r = regex(r"\b[0-9][0-9]?/[0-9][0-9]?/[0-9][0-9](?:[0-9][0-9])?\b");
  16. foreach(line; stdin.byLine)
  17. {
  18. // matchAll() returns a range that can be iterated
  19. // to get all subsequent matches.
  20. foreach(c; matchAll(line, r))
  21. writeln(c.hit);
  22. }
  23. }
  24. ...
  25. // Create a static regex at compile-time, which contains fast native code.
  26. auto ctr = ctRegex!(`^.*/([^/]+)/?$`);
  27. // It works just like a normal regex:
  28. auto c2 = matchFirst("foo/bar", ctr); // First match found here, if any
  29. assert(!c2.empty); // Be sure to check if there is a match before examining contents!
  30. assert(c2[1] == "bar"); // Captures is a range of submatches: 0 = full match.
  31. ...
  32. // The result of the $(D matchAll) is directly testable with if/assert/while.
  33. // e.g. test if a string consists of letters:
  34. assert(matchFirst("Letter", `^\p{L}+$`));
  35. ---
  36. $(SECTION Syntax and general information)
  37. The general usage guideline is to keep regex complexity on the side of simplicity,
  38. as its capabilities reside in purely character-level manipulation.
  39. As such it's ill-suited for tasks involving higher level invariants
  40. like matching an integer number $(U bounded) in an [a,b] interval.
  41. Checks of this sort of are better addressed by additional post-processing.
  42. The basic syntax shouldn't surprise experienced users of regular expressions.
  43. For an introduction to $(D std.regex) see a
  44. $(WEB dlang.org/regular-expression.html, short tour) of the module API
  45. and its abilities.
  46. There are other web resources on regular expressions to help newcomers,
  47. and a good $(WEB www.regular-expressions.info, reference with tutorial)
  48. can easily be found.
  49. This library uses a remarkably common ECMAScript syntax flavor
  50. with the following extensions:
  51. $(UL
  52. $(LI Named subexpressions, with Python syntax. )
  53. $(LI Unicode properties such as Scripts, Blocks and common binary properties e.g Alphabetic, White_Space, Hex_Digit etc.)
  54. $(LI Arbitrary length and complexity lookbehind, including lookahead in lookbehind and vise-versa.)
  55. )
  56. $(REG_START Pattern syntax )
  57. $(I std.regex operates on codepoint level,
  58. 'character' in this table denotes a single Unicode codepoint.)
  59. $(REG_TABLE
  60. $(REG_TITLE Pattern element, Semantics )
  61. $(REG_TITLE Atoms, Match single characters )
  62. $(REG_ROW any character except [{|*+?()^$, Matches the character itself. )
  63. $(REG_ROW ., In single line mode matches any character.
  64. Otherwise it matches any character except '\n' and '\r'. )
  65. $(REG_ROW [class], Matches a single character
  66. that belongs to this character class. )
  67. $(REG_ROW [^class], Matches a single character that
  68. does $(U not) belong to this character class.)
  69. $(REG_ROW \cC, Matches the control character corresponding to letter C)
  70. $(REG_ROW \xXX, Matches a character with hexadecimal value of XX. )
  71. $(REG_ROW \uXXXX, Matches a character with hexadecimal value of XXXX. )
  72. $(REG_ROW \U00YYYYYY, Matches a character with hexadecimal value of YYYYYY. )
  73. $(REG_ROW \f, Matches a formfeed character. )
  74. $(REG_ROW \n, Matches a linefeed character. )
  75. $(REG_ROW \r, Matches a carriage return character. )
  76. $(REG_ROW \t, Matches a tab character. )
  77. $(REG_ROW \v, Matches a vertical tab character. )
  78. $(REG_ROW \d, Matches any Unicode digit. )
  79. $(REG_ROW \D, Matches any character except Unicode digits. )
  80. $(REG_ROW \w, Matches any word character (note: this includes numbers).)
  81. $(REG_ROW \W, Matches any non-word character.)
  82. $(REG_ROW \s, Matches whitespace, same as \p{White_Space}.)
  83. $(REG_ROW \S, Matches any character except those recognized as $(I \s ). )
  84. $(REG_ROW \\, Matches \ character. )
  85. $(REG_ROW \c where c is one of [|*+?(), Matches the character c itself. )
  86. $(REG_ROW \p{PropertyName}, Matches a character that belongs
  87. to the Unicode PropertyName set.
  88. Single letter abbreviations can be used without surrounding {,}. )
  89. $(REG_ROW \P{PropertyName}, Matches a character that does not belong
  90. to the Unicode PropertyName set.
  91. Single letter abbreviations can be used without surrounding {,}. )
  92. $(REG_ROW \p{InBasicLatin}, Matches any character that is part of
  93. the BasicLatin Unicode $(U block).)
  94. $(REG_ROW \P{InBasicLatin}, Matches any character except ones in
  95. the BasicLatin Unicode $(U block).)
  96. $(REG_ROW \p{Cyrillic}, Matches any character that is part of
  97. Cyrillic $(U script).)
  98. $(REG_ROW \P{Cyrillic}, Matches any character except ones in
  99. Cyrillic $(U script).)
  100. $(REG_TITLE Quantifiers, Specify repetition of other elements)
  101. $(REG_ROW *, Matches previous character/subexpression 0 or more times.
  102. Greedy version - tries as many times as possible.)
  103. $(REG_ROW *?, Matches previous character/subexpression 0 or more times.
  104. Lazy version - stops as early as possible.)
  105. $(REG_ROW +, Matches previous character/subexpression 1 or more times.
  106. Greedy version - tries as many times as possible.)
  107. $(REG_ROW +?, Matches previous character/subexpression 1 or more times.
  108. Lazy version - stops as early as possible.)
  109. $(REG_ROW {n}, Matches previous character/subexpression exactly n times. )
  110. $(REG_ROW {n&#44}, Matches previous character/subexpression n times or more.
  111. Greedy version - tries as many times as possible. )
  112. $(REG_ROW {n&#44}?, Matches previous character/subexpression n times or more.
  113. Lazy version - stops as early as possible.)
  114. $(REG_ROW {n&#44m}, Matches previous character/subexpression n to m times.
  115. Greedy version - tries as many times as possible, but no more than m times. )
  116. $(REG_ROW {n&#44m}?, Matches previous character/subexpression n to m times.
  117. Lazy version - stops as early as possible, but no less then n times.)
  118. $(REG_TITLE Other, Subexpressions & alternations )
  119. $(REG_ROW (regex), Matches subexpression regex,
  120. saving matched portion of text for later retrieval. )
  121. $(REG_ROW (?:regex), Matches subexpression regex,
  122. $(U not) saving matched portion of text. Useful to speed up matching. )
  123. $(REG_ROW A|B, Matches subexpression A, or failing that, matches B. )
  124. $(REG_ROW (?P<name>regex), Matches named subexpression
  125. regex labeling it with name 'name'.
  126. When referring to a matched portion of text,
  127. names work like aliases in addition to direct numbers.
  128. )
  129. $(REG_TITLE Assertions, Match position rather than character )
  130. $(REG_ROW ^, Matches at the begining of input or line (in multiline mode).)
  131. $(REG_ROW $, Matches at the end of input or line (in multiline mode). )
  132. $(REG_ROW \b, Matches at word boundary. )
  133. $(REG_ROW \B, Matches when $(U not) at word boundary. )
  134. $(REG_ROW (?=regex), Zero-width lookahead assertion.
  135. Matches at a point where the subexpression
  136. regex could be matched starting from the current position.
  137. )
  138. $(REG_ROW (?!regex), Zero-width negative lookahead assertion.
  139. Matches at a point where the subexpression
  140. regex could $(U not) be matched starting from the current position.
  141. )
  142. $(REG_ROW (?<=regex), Zero-width lookbehind assertion. Matches at a point
  143. where the subexpression regex could be matched ending
  144. at the current position (matching goes backwards).
  145. )
  146. $(REG_ROW (?<!regex), Zero-width negative lookbehind assertion.
  147. Matches at a point where the subexpression regex could $(U not)
  148. be matched ending at the current position (matching goes backwards).
  149. )
  150. )
  151. $(REG_START Character classes )
  152. $(REG_TABLE
  153. $(REG_TITLE Pattern element, Semantics )
  154. $(REG_ROW Any atom, Has the same meaning as outside of a character class.)
  155. $(REG_ROW a-z, Includes characters a, b, c, ..., z. )
  156. $(REG_ROW [a||b]&#44 [a--b]&#44 [a~~b]&#44 [a&&b], Where a, b are arbitrary classes,
  157. means union, set difference, symmetric set difference, and intersection respectively.
  158. $(I Any sequence of character class elements implicitly forms a union.) )
  159. )
  160. $(REG_START Regex flags )
  161. $(REG_TABLE
  162. $(REG_TITLE Flag, Semantics )
  163. $(REG_ROW g, Global regex, repeat over the whole input. )
  164. $(REG_ROW i, Case insensitive matching. )
  165. $(REG_ROW m, Multi-line mode, match ^, $ on start and end line separators
  166. as well as start and end of input.)
  167. $(REG_ROW s, Single-line mode, makes . match '\n' and '\r' as well. )
  168. $(REG_ROW x, Free-form syntax, ignores whitespace in pattern,
  169. useful for formatting complex regular expressions. )
  170. )
  171. $(SECTION Unicode support)
  172. This library provides full Level 1 support* according to
  173. $(WEB unicode.org/reports/tr18/, UTS 18). Specifically:
  174. $(UL
  175. $(LI 1.1 Hex notation via any of \uxxxx, \U00YYYYYY, \xZZ.)
  176. $(LI 1.2 Unicode properties.)
  177. $(LI 1.3 Character classes with set operations.)
  178. $(LI 1.4 Word boundaries use the full set of "word" characters.)
  179. $(LI 1.5 Using simple casefolding to match case
  180. insensitively across the full range of codepoints.)
  181. $(LI 1.6 Respecting line breaks as any of
  182. \u000A | \u000B | \u000C | \u000D | \u0085 | \u2028 | \u2029 | \u000D\u000A.)
  183. $(LI 1.7 Operating on codepoint level.)
  184. )
  185. *With exception of point 1.1.1, as of yet, normalization of input
  186. is expected to be enforced by user.
  187. $(SECTION Replace format string)
  188. A set of functions in this module that do the substitution rely
  189. on a simple format to guide the process. In particular the table below
  190. applies to the $(D format) argument of
  191. $(LREF replaceFirst) and $(LREF replaceAll).
  192. The format string can reference parts of match using the following notation.
  193. $(REG_TABLE
  194. $(REG_TITLE Format specifier, Replaced by )
  195. $(REG_ROW $&amp;, the whole match. )
  196. $(REG_ROW $`, part of input $(I preceding) the match. )
  197. $(REG_ROW $', part of input $(I following) the match. )
  198. $(REG_ROW $$, '$' character. )
  199. $(REG_ROW \c &#44 where c is any character, the character c itself. )
  200. $(REG_ROW \\, '\' character. )
  201. $(REG_ROW &#36;1 .. &#36;99, submatch number 1 to 99 respectively. )
  202. )
  203. $(SECTION Slicing and zero memory allocations orientation)
  204. All matches returned by pattern matching functionality in this library
  205. are slices of the original input. The notable exception is the $(D replace)
  206. family of functions that generate a new string from the input.
  207. In cases where producing the replacement is the ultimate goal
  208. $(LREF replaceFirstInto) and $(LREF replaceAllInto) could come in handy
  209. as functions that avoid allocations even for replacement.
  210. Copyright: Copyright Dmitry Olshansky, 2011-
  211. License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
  212. Authors: Dmitry Olshansky,
  213. API and utility constructs are modeled after the original $(D std.regex)
  214. by Walter Bright and Andrei Alexandrescu.
  215. Source: $(PHOBOSSRC std/_regex.d)
  216. Macros:
  217. REG_ROW = $(TR $(TD $(I $1 )) $(TD $+) )
  218. REG_TITLE = $(TR $(TD $(B $1)) $(TD $(B $2)) )
  219. REG_TABLE = <table border="1" cellspacing="0" cellpadding="5" > $0 </table>
  220. REG_START = <h3><div align="center"> $0 </div></h3>
  221. SECTION = <h3><a id="$1">$0</a></h3>
  222. S_LINK = <a href="#$1">$+</a>
  223. +/
  224. module std.regex;
  225. import std.regex.internal.ir;
  226. import std.regex.internal.thompson; //TODO: get rid of this dependency
  227. import std.exception, std.traits, std.range;
  228. /++
  229. $(D Regex) object holds regular expression pattern in compiled form.
  230. Instances of this object are constructed via calls to $(D regex).
  231. This is an intended form for caching and storage of frequently
  232. used regular expressions.
  233. Examples:
  234. Test if this object doesn't contain any compiled pattern.
  235. ---
  236. Regex!char r;
  237. assert(r.empty);
  238. r = regex(""); // Note: "" is a valid regex pattern.
  239. assert(!r.empty);
  240. ---
  241. Getting a range of all the named captures in the regex.
  242. ----
  243. import std.range;
  244. import std.algorithm;
  245. auto re = regex(`(?P<name>\w+) = (?P<var>\d+)`);
  246. auto nc = re.namedCaptures;
  247. static assert(isRandomAccessRange!(typeof(nc)));
  248. assert(!nc.empty);
  249. assert(nc.length == 2);
  250. assert(nc.equal(["name", "var"]));
  251. assert(nc[0] == "name");
  252. assert(nc[1..$].equal(["var"]));
  253. ----
  254. +/
  255. public alias Regex(Char) = std.regex.internal.ir.Regex!(Char);
  256. /++
  257. A $(D StaticRegex) is $(D Regex) object that contains D code specially
  258. generated at compile-time to speed up matching.
  259. Implicitly convertible to normal $(D Regex),
  260. however doing so will result in losing this additional capability.
  261. +/
  262. public alias StaticRegex(Char) = std.regex.internal.ir.StaticRegex!(Char);
  263. /++
  264. Compile regular expression pattern for the later execution.
  265. Returns: $(D Regex) object that works on inputs having
  266. the same character width as $(D pattern).
  267. Params:
  268. pattern = Regular expression
  269. flags = The _attributes (g, i, m and x accepted)
  270. Throws: $(D RegexException) if there were any errors during compilation.
  271. +/
  272. @trusted public auto regex(S)(S pattern, const(char)[] flags="")
  273. if(isSomeString!(S))
  274. {
  275. import std.functional;
  276. enum cacheSize = 8; //TODO: invent nice interface to control regex caching
  277. if(__ctfe)
  278. return regexImpl(pattern, flags);
  279. return memoize!(regexImpl!S, cacheSize)(pattern, flags);
  280. }
  281. public auto regexImpl(S)(S pattern, const(char)[] flags="")
  282. if(isSomeString!(S))
  283. {
  284. import std.regex.internal.parser;
  285. auto parser = Parser!(Unqual!(typeof(pattern)))(pattern, flags);
  286. auto r = parser.program;
  287. return r;
  288. }
  289. template ctRegexImpl(alias pattern, string flags=[])
  290. {
  291. import std.regex.internal.parser, std.regex.internal.backtracking;
  292. enum r = regex(pattern, flags);
  293. alias Char = BasicElementOf!(typeof(pattern));
  294. enum source = ctGenRegExCode(r);
  295. alias Matcher = BacktrackingMatcher!(true);
  296. @trusted bool func(ref Matcher!Char matcher)
  297. {
  298. debug(std_regex_ctr) pragma(msg, source);
  299. mixin(source);
  300. }
  301. enum nr = StaticRegex!Char(r, &func);
  302. }
  303. /++
  304. Compile regular expression using CTFE
  305. and generate optimized native machine code for matching it.
  306. Returns: StaticRegex object for faster matching.
  307. Params:
  308. pattern = Regular expression
  309. flags = The _attributes (g, i, m and x accepted)
  310. +/
  311. public enum ctRegex(alias pattern, alias flags=[]) = ctRegexImpl!(pattern, flags).nr;
  312. enum isRegexFor(RegEx, R) = is(RegEx == Regex!(BasicElementOf!R))
  313. || is(RegEx == StaticRegex!(BasicElementOf!R));
  314. /++
  315. $(D Captures) object contains submatches captured during a call
  316. to $(D match) or iteration over $(D RegexMatch) range.
  317. First element of range is the whole match.
  318. +/
  319. @trusted public struct Captures(R, DIndex = size_t)
  320. if(isSomeString!R)
  321. {//@trusted because of union inside
  322. alias DataIndex = DIndex;
  323. alias String = R;
  324. private:
  325. import std.conv;
  326. R _input;
  327. bool _empty;
  328. enum smallString = 3;
  329. union
  330. {
  331. Group!DataIndex[] big_matches;
  332. Group!DataIndex[smallString] small_matches;
  333. }
  334. uint _f, _b;
  335. uint _ngroup;
  336. NamedGroup[] _names;
  337. this()(R input, uint ngroups, NamedGroup[] named)
  338. {
  339. _input = input;
  340. _ngroup = ngroups;
  341. _names = named;
  342. newMatches();
  343. _b = _ngroup;
  344. _f = 0;
  345. }
  346. this(alias Engine)(ref RegexMatch!(R,Engine) rmatch)
  347. {
  348. _input = rmatch._input;
  349. _ngroup = rmatch._engine.re.ngroup;
  350. _names = rmatch._engine.re.dict;
  351. newMatches();
  352. _b = _ngroup;
  353. _f = 0;
  354. }
  355. @property Group!DataIndex[] matches()
  356. {
  357. return _ngroup > smallString ? big_matches : small_matches[0 .. _ngroup];
  358. }
  359. void newMatches()
  360. {
  361. if(_ngroup > smallString)
  362. big_matches = new Group!DataIndex[_ngroup];
  363. }
  364. public:
  365. ///Slice of input prior to the match.
  366. @property R pre()
  367. {
  368. return _empty ? _input[] : _input[0 .. matches[0].begin];
  369. }
  370. ///Slice of input immediately after the match.
  371. @property R post()
  372. {
  373. return _empty ? _input[] : _input[matches[0].end .. $];
  374. }
  375. ///Slice of matched portion of input.
  376. @property R hit()
  377. {
  378. assert(!_empty);
  379. return _input[matches[0].begin .. matches[0].end];
  380. }
  381. ///Range interface.
  382. @property R front()
  383. {
  384. assert(!empty);
  385. return _input[matches[_f].begin .. matches[_f].end];
  386. }
  387. ///ditto
  388. @property R back()
  389. {
  390. assert(!empty);
  391. return _input[matches[_b - 1].begin .. matches[_b - 1].end];
  392. }
  393. ///ditto
  394. void popFront()
  395. {
  396. assert(!empty);
  397. ++_f;
  398. }
  399. ///ditto
  400. void popBack()
  401. {
  402. assert(!empty);
  403. --_b;
  404. }
  405. ///ditto
  406. @property bool empty() const { return _empty || _f >= _b; }
  407. ///ditto
  408. R opIndex()(size_t i) /*const*/ //@@@BUG@@@
  409. {
  410. assert(_f + i < _b,text("requested submatch number ", i," is out of range"));
  411. assert(matches[_f + i].begin <= matches[_f + i].end,
  412. text("wrong match: ", matches[_f + i].begin, "..", matches[_f + i].end));
  413. return _input[matches[_f + i].begin .. matches[_f + i].end];
  414. }
  415. /++
  416. Explicit cast to bool.
  417. Useful as a shorthand for !(x.empty) in if and assert statements.
  418. ---
  419. import std.regex;
  420. assert(!matchFirst("nothing", "something"));
  421. ---
  422. +/
  423. @safe bool opCast(T:bool)() const nothrow { return !empty; }
  424. /++
  425. Lookup named submatch.
  426. ---
  427. import std.regex;
  428. import std.range;
  429. auto c = matchFirst("a = 42;", regex(`(?P<var>\w+)\s*=\s*(?P<value>\d+);`));
  430. assert(c["var"] == "a");
  431. assert(c["value"] == "42");
  432. popFrontN(c, 2);
  433. //named groups are unaffected by range primitives
  434. assert(c["var"] =="a");
  435. assert(c.front == "42");
  436. ----
  437. +/
  438. R opIndex(String)(String i) /*const*/ //@@@BUG@@@
  439. if(isSomeString!String)
  440. {
  441. size_t index = lookupNamedGroup(_names, i);
  442. return _input[matches[index].begin .. matches[index].end];
  443. }
  444. ///Number of matches in this object.
  445. @property size_t length() const { return _empty ? 0 : _b - _f; }
  446. ///A hook for compatibility with original std.regex.
  447. @property ref captures(){ return this; }
  448. }
  449. ///
  450. unittest
  451. {
  452. auto c = matchFirst("@abc#", regex(`(\w)(\w)(\w)`));
  453. assert(c.pre == "@"); // Part of input preceding match
  454. assert(c.post == "#"); // Immediately after match
  455. assert(c.hit == c[0] && c.hit == "abc"); // The whole match
  456. assert(c[2] == "b");
  457. assert(c.front == "abc");
  458. c.popFront();
  459. assert(c.front == "a");
  460. assert(c.back == "c");
  461. c.popBack();
  462. assert(c.back == "b");
  463. popFrontN(c, 2);
  464. assert(c.empty);
  465. assert(!matchFirst("nothing", "something"));
  466. }
  467. /++
  468. A regex engine state, as returned by $(D match) family of functions.
  469. Effectively it's a forward range of Captures!R, produced
  470. by lazily searching for matches in a given input.
  471. $(D alias Engine) specifies an engine type to use during matching,
  472. and is automatically deduced in a call to $(D match)/$(D bmatch).
  473. +/
  474. @trusted public struct RegexMatch(R, alias Engine = ThompsonMatcher)
  475. if(isSomeString!R)
  476. {
  477. private:
  478. import core.stdc.stdlib;
  479. alias Char = BasicElementOf!R;
  480. alias EngineType = Engine!Char;
  481. EngineType _engine;
  482. R _input;
  483. Captures!(R,EngineType.DataIndex) _captures;
  484. void[] _memory;//is ref-counted
  485. this(RegEx)(R input, RegEx prog)
  486. {
  487. _input = input;
  488. immutable size = EngineType.initialMemory(prog)+size_t.sizeof;
  489. _memory = (enforce(malloc(size))[0..size]);
  490. scope(failure) free(_memory.ptr);
  491. *cast(size_t*)_memory.ptr = 1;
  492. _engine = EngineType(prog, Input!Char(input), _memory[size_t.sizeof..$]);
  493. static if(is(RegEx == StaticRegex!(BasicElementOf!R)))
  494. _engine.nativeFn = prog.nativeFn;
  495. _captures = Captures!(R,EngineType.DataIndex)(this);
  496. _captures._empty = !_engine.match(_captures.matches);
  497. debug(std_regex_allocation) writefln("RefCount (ctor): %x %d", _memory.ptr, counter);
  498. }
  499. @property ref size_t counter(){ return *cast(size_t*)_memory.ptr; }
  500. public:
  501. this(this)
  502. {
  503. if(_memory.ptr)
  504. {
  505. ++counter;
  506. debug(std_regex_allocation) writefln("RefCount (postblit): %x %d",
  507. _memory.ptr, *cast(size_t*)_memory.ptr);
  508. }
  509. }
  510. ~this()
  511. {
  512. if(_memory.ptr && --*cast(size_t*)_memory.ptr == 0)
  513. {
  514. debug(std_regex_allocation) writefln("RefCount (dtor): %x %d",
  515. _memory.ptr, *cast(size_t*)_memory.ptr);
  516. free(cast(void*)_memory.ptr);
  517. }
  518. }
  519. ///Shorthands for front.pre, front.post, front.hit.
  520. @property R pre()
  521. {
  522. return _captures.pre;
  523. }
  524. ///ditto
  525. @property R post()
  526. {
  527. return _captures.post;
  528. }
  529. ///ditto
  530. @property R hit()
  531. {
  532. return _captures.hit;
  533. }
  534. /++
  535. Functionality for processing subsequent matches of global regexes via range interface:
  536. ---
  537. import std.regex;
  538. auto m = matchAll("Hello, world!", regex(`\w+`));
  539. assert(m.front.hit == "Hello");
  540. m.popFront();
  541. assert(m.front.hit == "world");
  542. m.popFront();
  543. assert(m.empty);
  544. ---
  545. +/
  546. @property auto front()
  547. {
  548. return _captures;
  549. }
  550. ///ditto
  551. void popFront()
  552. {
  553. if(counter != 1)
  554. {//do cow magic first
  555. counter--;//we abandon this reference
  556. immutable size = EngineType.initialMemory(_engine.re)+size_t.sizeof;
  557. _memory = (enforce(malloc(size))[0..size]);
  558. _engine = _engine.dupTo(_memory[size_t.sizeof..size]);
  559. counter = 1;//points to new chunk
  560. }
  561. //previous _captures can have escaped references from Capture object
  562. _captures.newMatches();
  563. _captures._empty = !_engine.match(_captures.matches);
  564. }
  565. ///ditto
  566. auto save(){ return this; }
  567. ///Test if this match object is empty.
  568. @property bool empty(){ return _captures._empty; }
  569. ///Same as !(x.empty), provided for its convenience in conditional statements.
  570. T opCast(T:bool)(){ return !empty; }
  571. /// Same as .front, provided for compatibility with original std.regex.
  572. @property auto captures(){ return _captures; }
  573. }
  574. private @trusted auto matchOnce(alias Engine, RegEx, R)(R input, RegEx re)
  575. {
  576. import core.stdc.stdlib;
  577. alias Char = BasicElementOf!R;
  578. alias EngineType = Engine!Char;
  579. size_t size = EngineType.initialMemory(re);
  580. void[] memory = enforce(malloc(size))[0..size];
  581. scope(exit) free(memory.ptr);
  582. auto captures = Captures!(R, EngineType.DataIndex)(input, re.ngroup, re.dict);
  583. auto engine = EngineType(re, Input!Char(input), memory);
  584. static if(is(RegEx == StaticRegex!(BasicElementOf!R)))
  585. engine.nativeFn = re.nativeFn;
  586. captures._empty = !engine.match(captures.matches);
  587. return captures;
  588. }
  589. private auto matchMany(alias Engine, RegEx, R)(R input, RegEx re)
  590. {
  591. re.flags |= RegexOption.global;
  592. return RegexMatch!(R, Engine)(input, re);
  593. }
  594. unittest
  595. {
  596. //sanity checks for new API
  597. auto re = regex("abc");
  598. assert(!"abc".matchOnce!(ThompsonMatcher)(re).empty);
  599. assert("abc".matchOnce!(ThompsonMatcher)(re)[0] == "abc");
  600. }
  601. private enum isReplaceFunctor(alias fun, R) =
  602. __traits(compiles, (Captures!R c) { fun(c); });
  603. // the lowest level - just stuff replacements into the sink
  604. private @trusted void replaceCapturesInto(alias output, Sink, R, T)
  605. (ref Sink sink, R input, T captures)
  606. if(isOutputRange!(Sink, dchar) && isSomeString!R)
  607. {
  608. sink.put(captures.pre);
  609. // a hack to get around bogus errors, should be simply output(captures, sink)
  610. // "is a nested function and cannot be accessed from"
  611. static if(isReplaceFunctor!(output, R))
  612. sink.put(output(captures)); //"mutator" type of function
  613. else
  614. output(captures, sink); //"output" type of function
  615. sink.put(captures.post);
  616. }
  617. // ditto for a range of captures
  618. private void replaceMatchesInto(alias output, Sink, R, T)
  619. (ref Sink sink, R input, T matches)
  620. if(isOutputRange!(Sink, dchar) && isSomeString!R)
  621. {
  622. size_t offset = 0;
  623. foreach(cap; matches)
  624. {
  625. sink.put(cap.pre[offset .. $]);
  626. // same hack, see replaceCapturesInto
  627. static if(isReplaceFunctor!(output, R))
  628. sink.put(output(cap)); //"mutator" type of function
  629. else
  630. output(cap, sink); //"output" type of function
  631. offset = cap.pre.length + cap.hit.length;
  632. }
  633. sink.put(input[offset .. $]);
  634. }
  635. // a general skeleton of replaceFirst
  636. private R replaceFirstWith(alias output, R, RegEx)(R input, RegEx re)
  637. if(isSomeString!R && isRegexFor!(RegEx, R))
  638. {
  639. auto data = matchFirst(input, re);
  640. if(data.empty)
  641. return input;
  642. auto app = appender!(R)();
  643. replaceCapturesInto!output(app, input, data);
  644. return app.data;
  645. }
  646. // ditto for replaceAll
  647. // the method parameter allows old API to ride on the back of the new one
  648. private R replaceAllWith(alias output,
  649. alias method=matchAll, R, RegEx)(R input, RegEx re)
  650. if(isSomeString!R && isRegexFor!(RegEx, R))
  651. {
  652. auto matches = method(input, re); //inout(C)[] fails
  653. if(matches.empty)
  654. return input;
  655. auto app = appender!(R)();
  656. replaceMatchesInto!output(app, input, matches);
  657. return app.data;
  658. }
  659. /++
  660. Start matching $(D input) to regex pattern $(D re),
  661. using Thompson NFA matching scheme.
  662. The use of this function is $(RED discouraged) - use either of
  663. $(LREF matchAll) or $(LREF matchFirst).
  664. Delegating the kind of operation
  665. to "g" flag is soon to be phased out along with the
  666. ability to choose the exact matching scheme. The choice of
  667. matching scheme to use depends highly on the pattern kind and
  668. can done automatically on case by case basis.
  669. Returns: a $(D RegexMatch) object holding engine state after first match.
  670. +/
  671. public auto match(R, RegEx)(R input, RegEx re)
  672. if(isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)))
  673. {
  674. import std.regex.internal.thompson;
  675. return RegexMatch!(Unqual!(typeof(input)),ThompsonMatcher)(input, re);
  676. }
  677. ///ditto
  678. public auto match(R, String)(R input, String re)
  679. if(isSomeString!R && isSomeString!String)
  680. {
  681. import std.regex.internal.thompson;
  682. return RegexMatch!(Unqual!(typeof(input)),ThompsonMatcher)(input, regex(re));
  683. }
  684. public auto match(R, RegEx)(R input, RegEx re)
  685. if(isSomeString!R && is(RegEx == StaticRegex!(BasicElementOf!R)))
  686. {
  687. import std.regex.internal.backtracking;
  688. return RegexMatch!(Unqual!(typeof(input)),BacktrackingMatcher!true)(input, re);
  689. }
  690. /++
  691. Find the first (leftmost) slice of the $(D input) that
  692. matches the pattern $(D re). This function picks the most suitable
  693. regular expression engine depending on the pattern properties.
  694. $(D re) parameter can be one of three types:
  695. $(UL
  696. $(LI Plain string, in which case it's compiled to bytecode before matching. )
  697. $(LI Regex!char (wchar/dchar) that contains a pattern in the form of
  698. compiled bytecode. )
  699. $(LI StaticRegex!char (wchar/dchar) that contains a pattern in the form of
  700. compiled native machine code. )
  701. )
  702. Returns:
  703. $(LREF Captures) containing the extent of a match together with all submatches
  704. if there was a match, otherwise an empty $(LREF Captures) object.
  705. +/
  706. public auto matchFirst(R, RegEx)(R input, RegEx re)
  707. if(isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)))
  708. {
  709. import std.regex.internal.thompson;
  710. return matchOnce!ThompsonMatcher(input, re);
  711. }
  712. ///ditto
  713. public auto matchFirst(R, String)(R input, String re)
  714. if(isSomeString!R && isSomeString!String)
  715. {
  716. import std.regex.internal.thompson;
  717. return matchOnce!ThompsonMatcher(input, regex(re));
  718. }
  719. public auto matchFirst(R, RegEx)(R input, RegEx re)
  720. if(isSomeString!R && is(RegEx == StaticRegex!(BasicElementOf!R)))
  721. {
  722. import std.regex.internal.backtracking;
  723. return matchOnce!(BacktrackingMatcher!true)(input, re);
  724. }
  725. /++
  726. Initiate a search for all non-overlapping matches to the pattern $(D re)
  727. in the given $(D input). The result is a lazy range of matches generated
  728. as they are encountered in the input going left to right.
  729. This function picks the most suitable regular expression engine
  730. depending on the pattern properties.
  731. $(D re) parameter can be one of three types:
  732. $(UL
  733. $(LI Plain string, in which case it's compiled to bytecode before matching. )
  734. $(LI Regex!char (wchar/dchar) that contains a pattern in the form of
  735. compiled bytecode. )
  736. $(LI StaticRegex!char (wchar/dchar) that contains a pattern in the form of
  737. compiled native machine code. )
  738. )
  739. Returns:
  740. $(LREF RegexMatch) object that represents matcher state
  741. after the first match was found or an empty one if not present.
  742. +/
  743. public auto matchAll(R, RegEx)(R input, RegEx re)
  744. if(isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)))
  745. {
  746. import std.regex.internal.thompson;
  747. return matchMany!ThompsonMatcher(input, re);
  748. }
  749. ///ditto
  750. public auto matchAll(R, String)(R input, String re)
  751. if(isSomeString!R && isSomeString!String)
  752. {
  753. import std.regex.internal.thompson;
  754. return matchMany!ThompsonMatcher(input, regex(re));
  755. }
  756. public auto matchAll(R, RegEx)(R input, RegEx re)
  757. if(isSomeString!R && is(RegEx == StaticRegex!(BasicElementOf!R)))
  758. {
  759. import std.regex.internal.backtracking;
  760. return matchMany!(BacktrackingMatcher!true)(input, re);
  761. }
  762. // another set of tests just to cover the new API
  763. @system unittest
  764. {
  765. import std.conv : to;
  766. import std.algorithm : map, equal;
  767. foreach(String; TypeTuple!(string, wstring, const(dchar)[]))
  768. {
  769. auto str1 = "blah-bleh".to!String();
  770. auto pat1 = "bl[ae]h".to!String();
  771. auto mf = matchFirst(str1, pat1);
  772. assert(mf.equal(["blah".to!String()]));
  773. auto mAll = matchAll(str1, pat1);
  774. assert(mAll.equal!((a,b) => a.equal(b))
  775. ([["blah".to!String()], ["bleh".to!String()]]));
  776. auto str2 = "1/03/12 - 3/03/12".to!String();
  777. auto pat2 = regex(r"(\d+)/(\d+)/(\d+)".to!String());
  778. auto mf2 = matchFirst(str2, pat2);
  779. assert(mf2.equal(["1/03/12", "1", "03", "12"].map!(to!String)()));
  780. auto mAll2 = matchAll(str2, pat2);
  781. assert(mAll2.front.equal(mf2));
  782. mAll2.popFront();
  783. assert(mAll2.front.equal(["3/03/12", "3", "03", "12"].map!(to!String)()));
  784. mf2.popFrontN(3);
  785. assert(mf2.equal(["12".to!String()]));
  786. auto ctPat = ctRegex!(`(?P<Quot>\d+)/(?P<Denom>\d+)`.to!String());
  787. auto str = "2 + 34/56 - 6/1".to!String();
  788. auto cmf = matchFirst(str, ctPat);
  789. assert(cmf.equal(["34/56", "34", "56"].map!(to!String)()));
  790. assert(cmf["Quot"] == "34".to!String());
  791. assert(cmf["Denom"] == "56".to!String());
  792. auto cmAll = matchAll(str, ctPat);
  793. assert(cmAll.front.equal(cmf));
  794. cmAll.popFront();
  795. assert(cmAll.front.equal(["6/1", "6", "1"].map!(to!String)()));
  796. }
  797. }
  798. /++
  799. Start matching of $(D input) to regex pattern $(D re),
  800. using traditional $(LUCKY backtracking) matching scheme.
  801. The use of this function is $(RED discouraged) - use either of
  802. $(LREF matchAll) or $(LREF matchFirst).
  803. Delegating the kind of operation
  804. to "g" flag is soon to be phased out along with the
  805. ability to choose the exact matching scheme. The choice of
  806. matching scheme to use depends highly on the pattern kind and
  807. can done automatically on case by case basis.
  808. Returns: a $(D RegexMatch) object holding engine
  809. state after first match.
  810. +/
  811. public auto bmatch(R, RegEx)(R input, RegEx re)
  812. if(isSomeString!R && is(RegEx == Regex!(BasicElementOf!R)))
  813. {
  814. import std.regex.internal.backtracking;
  815. return RegexMatch!(Unqual!(typeof(input)), BacktrackingMatcher!false)(input, re);
  816. }
  817. ///ditto
  818. public auto bmatch(R, String)(R input, String re)
  819. if(isSomeString!R && isSomeString!String)
  820. {
  821. import std.regex.internal.backtracking;
  822. return RegexMatch!(Unqual!(typeof(input)), BacktrackingMatcher!false)(input, regex(re));
  823. }
  824. public auto bmatch(R, RegEx)(R input, RegEx re)
  825. if(isSomeString!R && is(RegEx == StaticRegex!(BasicElementOf!R)))
  826. {
  827. import std.regex.internal.backtracking;
  828. return RegexMatch!(Unqual!(typeof(input)),BacktrackingMatcher!true)(input, re);
  829. }
  830. // produces replacement string from format using captures for substitution
  831. package void replaceFmt(R, Capt, OutR)
  832. (R format, Capt captures, OutR sink, bool ignoreBadSubs = false)
  833. if(isOutputRange!(OutR, ElementEncodingType!R[]) &&
  834. isOutputRange!(OutR, ElementEncodingType!(Capt.String)[]))
  835. {
  836. import std.algorithm, std.conv;
  837. enum State { Normal, Dollar }
  838. auto state = State.Normal;
  839. size_t offset;
  840. L_Replace_Loop:
  841. while(!format.empty)
  842. final switch(state)
  843. {
  844. case State.Normal:
  845. for(offset = 0; offset < format.length; offset++)//no decoding
  846. {
  847. if(format[offset] == '$')
  848. {
  849. state = State.Dollar;
  850. sink.put(format[0 .. offset]);
  851. format = format[offset+1 .. $];//ditto
  852. continue L_Replace_Loop;
  853. }
  854. }
  855. sink.put(format[0 .. offset]);
  856. format = format[offset .. $];
  857. break;
  858. case State.Dollar:
  859. if(std.ascii.isDigit(format[0]))
  860. {
  861. uint digit = parse!uint(format);
  862. enforce(ignoreBadSubs || digit < captures.length, text("invalid submatch number ", digit));
  863. if(digit < captures.length)
  864. sink.put(captures[digit]);
  865. }
  866. else if(format[0] == '{')
  867. {
  868. auto x = find!(a => !std.ascii.isAlpha(a))(format[1..$]);
  869. enforce(!x.empty && x[0] == '}', "no matching '}' in replacement format");
  870. auto name = format[1 .. $ - x.length];
  871. format = x[1..$];
  872. enforce(!name.empty, "invalid name in ${...} replacement format");
  873. sink.put(captures[name]);
  874. }
  875. else if(format[0] == '&')
  876. {
  877. sink.put(captures[0]);
  878. format = format[1 .. $];
  879. }
  880. else if(format[0] == '`')
  881. {
  882. sink.put(captures.pre);
  883. format = format[1 .. $];
  884. }
  885. else if(format[0] == '\'')
  886. {
  887. sink.put(captures.post);
  888. format = format[1 .. $];
  889. }
  890. else if(format[0] == '$')
  891. {
  892. sink.put(format[0 .. 1]);
  893. format = format[1 .. $];
  894. }
  895. state = State.Normal;
  896. break;
  897. }
  898. enforce(state == State.Normal, "invalid format string in regex replace");
  899. }
  900. /++
  901. Construct a new string from $(D input) by replacing the first match with
  902. a string generated from it according to the $(D format) specifier.
  903. To replace all matches use $(LREF replaceAll).
  904. Params:
  905. input = string to search
  906. re = compiled regular expression to use
  907. format = format string to generate replacements from,
  908. see $(S_LINK Replace format string, the format string).
  909. Returns:
  910. A string of the same type with the first match (if any) replaced.
  911. If no match is found returns the input string itself.
  912. Example:
  913. ---
  914. assert(replaceFirst("noon", regex("n"), "[$&]") == "[n]oon");
  915. ---
  916. +/
  917. public R replaceFirst(R, C, RegEx)(R input, RegEx re, const(C)[] format)
  918. if(isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R))
  919. {
  920. return replaceFirstWith!((m, sink) => replaceFmt(format, m, sink))(input, re);
  921. }
  922. /++
  923. This is a general replacement tool that construct a new string by replacing
  924. matches of pattern $(D re) in the $(D input). Unlike the other overload
  925. there is no format string instead captures are passed to
  926. to a user-defined functor $(D fun) that returns a new string
  927. to use as replacement.
  928. This version replaces the first match in $(D input),
  929. see $(LREF replaceAll) to replace the all of the matches.
  930. Returns:
  931. A new string of the same type as $(D input) with all matches
  932. replaced by return values of $(D fun). If no matches found
  933. returns the $(D input) itself.
  934. Example:
  935. ---
  936. string list = "#21 out of 46";
  937. string newList = replaceFirst!(cap => to!string(to!int(cap.hit)+1))
  938. (list, regex(`[0-9]+`));
  939. assert(newList == "#22 out of 46");
  940. ---
  941. +/
  942. public R replaceFirst(alias fun, R, RegEx)(R input, RegEx re)
  943. if(isSomeString!R && isRegexFor!(RegEx, R))
  944. {
  945. return replaceFirstWith!((m, sink) => sink.put(fun(m)))(input, re);
  946. }
  947. /++
  948. A variation on $(LREF replaceFirst) that instead of allocating a new string
  949. on each call outputs the result piece-wise to the $(D sink). In particular
  950. this enables efficient construction of a final output incrementally.
  951. Like in $(LREF replaceFirst) family of functions there is an overload
  952. for the substitution guided by the $(D format) string
  953. and the one with the user defined callback.
  954. Example:
  955. ---
  956. import std.array;
  957. string m1 = "first message\n";
  958. string m2 = "second message\n";
  959. auto result = appender!string();
  960. replaceFirstInto(result, m1, regex(`([a-z]+) message`), "$1");
  961. //equivalent of the above with user-defined callback
  962. replaceFirstInto!(cap=>cap[1])(result, m2, regex(`([a-z]+) message`));
  963. assert(result.data == "first\nsecond\n");
  964. ---
  965. +/
  966. public @trusted void replaceFirstInto(Sink, R, C, RegEx)
  967. (ref Sink sink, R input, RegEx re, const(C)[] format)
  968. if(isOutputRange!(Sink, dchar) && isSomeString!R
  969. && is(C : dchar) && isRegexFor!(RegEx, R))
  970. {
  971. replaceCapturesInto!((m, sink) => replaceFmt(format, m, sink))
  972. (sink, input, matchFirst(input, re));
  973. }
  974. ///ditto
  975. public @trusted void replaceFirstInto(alias fun, Sink, R, RegEx)
  976. (Sink sink, R input, RegEx re)
  977. if(isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R))
  978. {
  979. replaceCapturesInto!fun(sink, input, matchFirst(input, re));
  980. }
  981. //examples for replaceFirst
  982. @system unittest
  983. {
  984. import std.conv;
  985. string list = "#21 out of 46";
  986. string newList = replaceFirst!(cap => to!string(to!int(cap.hit)+1))
  987. (list, regex(`[0-9]+`));
  988. assert(newList == "#22 out of 46");
  989. import std.array;
  990. string m1 = "first message\n";
  991. string m2 = "second message\n";
  992. auto result = appender!string();
  993. replaceFirstInto(result, m1, regex(`([a-z]+) message`), "$1");
  994. //equivalent of the above with user-defined callback
  995. replaceFirstInto!(cap=>cap[1])(result, m2, regex(`([a-z]+) message`));
  996. assert(result.data == "first\nsecond\n");
  997. }
  998. /++
  999. Construct a new string from $(D input) by replacing all of the
  1000. fragments that match a pattern $(D re) with a string generated
  1001. from the match according to the $(D format) specifier.
  1002. To replace only the first match use $(LREF replaceFirst).
  1003. Params:
  1004. input = string to search
  1005. re = compiled regular expression to use
  1006. format = format string to generate replacements from,
  1007. see $(S_LINK Replace format string, the format string).
  1008. Returns:
  1009. A string of the same type as $(D input) with the all
  1010. of the matches (if any) replaced.
  1011. If no match is found returns the input string itself.
  1012. Example:
  1013. ---
  1014. // Comify a number
  1015. auto com = regex(r"(?<=\d)(?=(\d\d\d)+\b)","g");
  1016. assert(replaceAll("12000 + 42100 = 54100", com, ",") == "12,000 + 42,100 = 54,100");
  1017. ---
  1018. +/
  1019. public @trusted R replaceAll(R, C, RegEx)(R input, RegEx re, const(C)[] format)
  1020. if(isSomeString!R && is(C : dchar) && isRegexFor!(RegEx, R))
  1021. {
  1022. return replaceAllWith!((m, sink) => replaceFmt(format, m, sink))(input, re);
  1023. }
  1024. /++
  1025. This is a general replacement tool that construct a new string by replacing
  1026. matches of pattern $(D re) in the $(D input). Unlike the other overload
  1027. there is no format string instead captures are passed to
  1028. to a user-defined functor $(D fun) that returns a new string
  1029. to use as replacement.
  1030. This version replaces all of the matches found in $(D input),
  1031. see $(LREF replaceFirst) to replace the first match only.
  1032. Returns:
  1033. A new string of the same type as $(D input) with all matches
  1034. replaced by return values of $(D fun). If no matches found
  1035. returns the $(D input) itself.
  1036. Params:
  1037. input = string to search
  1038. re = compiled regular expression
  1039. fun = delegate to use
  1040. Example:
  1041. Capitalize the letters 'a' and 'r':
  1042. ---
  1043. string baz(Captures!(string) m)
  1044. {
  1045. return std.string.toUpper(m.hit);
  1046. }
  1047. auto s = replaceAll!(baz)("Strap a rocket engine on a chicken.",
  1048. regex("[ar]"));
  1049. assert(s == "StRAp A Rocket engine on A chicken.");
  1050. ---
  1051. +/
  1052. public @trusted R replaceAll(alias fun, R, RegEx)(R input, RegEx re)
  1053. if(isSomeString!R && isRegexFor!(RegEx, R))
  1054. {
  1055. return replaceAllWith!((m, sink) => sink.put(fun(m)))(input, re);
  1056. }
  1057. /++
  1058. A variation on $(LREF replaceAll) that instead of allocating a new string
  1059. on each call outputs the result piece-wise to the $(D sink). In particular
  1060. this enables efficient construction of a final output incrementally.
  1061. As with $(LREF replaceAll) there are 2 overloads - one with a format string,
  1062. the other one with a user defined functor.
  1063. Example:
  1064. ---
  1065. //swap all 3 letter words and bring it back
  1066. string text = "How are you doing?";
  1067. auto sink = appender!(char[])();
  1068. replaceAllInto!(cap => retro(cap[0]))(sink, text, regex(`\b\w{3}\b`));
  1069. auto swapped = sink.data.dup; // make a copy explicitly
  1070. assert(swapped == "woH era uoy doing?");
  1071. sink.clear();
  1072. replaceAllInto!(cap => retro(cap[0]))(sink, swapped, regex(`\b\w{3}\b`));
  1073. assert(sink.data == text);
  1074. ---
  1075. +/
  1076. public @trusted void replaceAllInto(Sink, R, C, RegEx)
  1077. (Sink sink, R input, RegEx re, const(C)[] format)
  1078. if(isOutputRange!(Sink, dchar) && isSomeString!R
  1079. && is(C : dchar) && isRegexFor!(RegEx, R))
  1080. {
  1081. replaceMatchesInto!((m, sink) => replaceFmt(format, m, sink))
  1082. (sink, input, matchAll(input, re));
  1083. }
  1084. ///ditto
  1085. public @trusted void replaceAllInto(alias fun, Sink, R, RegEx)
  1086. (Sink sink, R input, RegEx re)
  1087. if(isOutputRange!(Sink, dchar) && isSomeString!R && isRegexFor!(RegEx, R))
  1088. {
  1089. replaceMatchesInto!fun(sink, input, matchAll(input, re));
  1090. }
  1091. // a bit of examples
  1092. @system unittest
  1093. {
  1094. //swap all 3 letter words and bring it back
  1095. string text = "How are you doing?";
  1096. auto sink = appender!(char[])();
  1097. replaceAllInto!(cap => retro(cap[0]))(sink, text, regex(`\b\w{3}\b`));
  1098. auto swapped = sink.data.dup; // make a copy explicitly
  1099. assert(swapped == "woH era uoy doing?");
  1100. sink.clear();
  1101. replaceAllInto!(cap => retro(cap[0]))(sink, swapped, regex(`\b\w{3}\b`));
  1102. assert(sink.data == text);
  1103. }
  1104. // exercise all of the replace APIs
  1105. @system unittest
  1106. {
  1107. import std.conv;
  1108. // try and check first/all simple substitution
  1109. foreach(S; TypeTuple!(string, wstring, dstring, char[], wchar[], dchar[]))
  1110. {
  1111. S s1 = "curt trial".to!S();
  1112. S s2 = "round dome".to!S();
  1113. S t1F = "court trial".to!S();
  1114. S t2F = "hound dome".to!S();
  1115. S t1A = "court trial".to!S();
  1116. S t2A = "hound home".to!S();
  1117. auto re1 = regex("curt".to!S());
  1118. auto re2 = regex("[dr]o".to!S());
  1119. assert(replaceFirst(s1, re1, "court") == t1F);
  1120. assert(replaceFirst(s2, re2, "ho") == t2F);
  1121. assert(replaceAll(s1, re1, "court") == t1A);
  1122. assert(replaceAll(s2, re2, "ho") == t2A);
  1123. auto rep1 = replaceFirst!(cap => cap[0][0]~"o".to!S()~cap[0][1..$])(s1, re1);
  1124. assert(rep1 == t1F);
  1125. assert(replaceFirst!(cap => "ho".to!S())(s2, re2) == t2F);
  1126. auto rep1A = replaceAll!(cap => cap[0][0]~"o".to!S()~cap[0][1..$])(s1, re1);
  1127. assert(rep1A == t1A);
  1128. assert(replaceAll!(cap => "ho".to!S())(s2, re2) == t2A);
  1129. auto sink = appender!S();
  1130. replaceFirstInto(sink, s1, re1, "court");
  1131. assert(sink.data == t1F);
  1132. replaceFirstInto(sink, s2, re2, "ho");
  1133. assert(sink.data == t1F~t2F);
  1134. replaceAllInto(sink, s1, re1, "court");
  1135. assert(sink.data == t1F~t2F~t1A);
  1136. replaceAllInto(sink, s2, re2, "ho");
  1137. assert(sink.data == t1F~t2F~t1A~t2A);
  1138. }
  1139. }
  1140. /++
  1141. Old API for replacement, operation depends on flags of pattern $(D re).
  1142. With "g" flag it performs the equivalent of $(LREF replaceAll) otherwise it
  1143. works the same as $(LREF replaceFirst).
  1144. The use of this function is $(RED discouraged), please use $(LREF replaceAll)
  1145. or $(LREF replaceFirst) explicitly.
  1146. +/
  1147. public R replace(alias scheme = match, R, C, RegEx)(R input, RegEx re, const(C)[] format)
  1148. if(isSomeString!R && isRegexFor!(RegEx, R))
  1149. {
  1150. return replaceAllWith!((m, sink) => replaceFmt(format, m, sink), match)(input, re);
  1151. }
  1152. ///ditto
  1153. public R replace(alias fun, R, RegEx)(R input, RegEx re)
  1154. if(isSomeString!R && isRegexFor!(RegEx, R))
  1155. {
  1156. return replaceAllWith!(fun, match)(input, re);
  1157. }
  1158. /++
  1159. Range that splits a string using a regular expression as a
  1160. separator.
  1161. Example:
  1162. ----
  1163. auto s1 = ", abc, de, fg, hi, ";
  1164. assert(equal(splitter(s1, regex(", *")),
  1165. ["", "abc", "de", "fg", "hi", ""]));
  1166. ----
  1167. +/
  1168. public struct Splitter(Range, alias RegEx = Regex)
  1169. if(isSomeString!Range && isRegexFor!(RegEx, Range))
  1170. {
  1171. private:
  1172. Range _input;
  1173. size_t _offset;
  1174. alias Rx = typeof(match(Range.init,RegEx.init));
  1175. Rx _match;
  1176. @trusted this(Range input, RegEx separator)
  1177. {//@@@BUG@@@ generated opAssign of RegexMatch is not @trusted
  1178. _input = input;
  1179. separator.flags |= RegexOption.global;
  1180. if (_input.empty)
  1181. {
  1182. //there is nothing to match at all, make _offset > 0
  1183. _offset = 1;
  1184. }
  1185. else
  1186. {
  1187. _match = Rx(_input, separator);
  1188. }
  1189. }
  1190. public:
  1191. auto ref opSlice()
  1192. {
  1193. return this.save;
  1194. }
  1195. ///Forward range primitives.
  1196. @property Range front()
  1197. {
  1198. import std.algorithm : min;
  1199. assert(!empty && _offset <= _match.pre.length
  1200. && _match.pre.length <= _input.length);
  1201. return _input[_offset .. min($, _match.pre.length)];
  1202. }
  1203. ///ditto
  1204. @property bool empty()
  1205. {
  1206. return _offset > _input.length;
  1207. }
  1208. ///ditto
  1209. void popFront()
  1210. {
  1211. assert(!empty);
  1212. if (_match.empty)
  1213. {
  1214. //No more separators, work is done here
  1215. _offset = _input.length + 1;
  1216. }
  1217. else
  1218. {
  1219. //skip past the separator
  1220. _offset = _match.pre.length + _match.hit.length;
  1221. _match.popFront();
  1222. }
  1223. }
  1224. ///ditto
  1225. @property auto save()
  1226. {
  1227. return this;
  1228. }
  1229. }
  1230. /**
  1231. A helper function, creates a $(D Splitter) on range $(D r) separated by regex $(D pat).
  1232. Captured subexpressions have no effect on the resulting range.
  1233. */
  1234. public Splitter!(Range, RegEx) splitter(Range, RegEx)(Range r, RegEx pat)
  1235. if(is(BasicElementOf!Range : dchar) && isRegexFor!(RegEx, Range))
  1236. {
  1237. return Splitter!(Range, RegEx)(r, pat);
  1238. }
  1239. ///An eager version of $(D splitter) that creates an array with splitted slices of $(D input).
  1240. public @trusted String[] split(String, RegEx)(String input, RegEx rx)
  1241. if(isSomeString!String && isRegexFor!(RegEx, String))
  1242. {
  1243. auto a = appender!(String[])();
  1244. foreach(e; splitter(input, rx))
  1245. a.put(e);
  1246. return a.data;
  1247. }
  1248. ///Exception object thrown in case of errors during regex compilation.
  1249. public alias RegexException = std.regex.internal.ir.RegexException;