PageRenderTime 85ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/std/regex/package.d

http://github.com/andralex/phobos
D | 1726 lines | 1376 code | 4 blank | 346 comment | 4 complexity | 1cee285ee3fd621f5fa315d2eedaed5d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file