PageRenderTime 58ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/std/regex/package.d

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

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