tpcre.pp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. program tpcre;
  2. {$mode objfpc}
  3. {$h+}
  4. { $DEFINE USE_WIDESTRING}
  5. uses
  6. {$IFNDEF USE_WIDESTRING}
  7. libpcre2_8,
  8. {$ELSE}
  9. libpcre2_16,
  10. {$ENDIF}
  11. ctypes;
  12. {$IFNDEF USE_WIDESTRING}
  13. function GetStrLen(p : PAnsiChar; len : Integer) : AnsiString;
  14. var
  15. L : Integer;
  16. begin
  17. Result:='';
  18. L:=StrLen(P);
  19. if L>len then
  20. L:=Len;
  21. SetLength(Result,L);
  22. if Len>0 then
  23. Move(P^,Result[1],L);
  24. end;
  25. {$ELSE}
  26. function GetStrLen(p : PWideChar; len : Integer) : UnicodeString;
  27. var
  28. L : Integer;
  29. P2: PWideChar;
  30. begin
  31. Result:='';
  32. L:=0;
  33. P2:=P;
  34. // No widestring strlen unless we compile in unicode rtl...
  35. While (P2^<>#0) do
  36. begin
  37. inc(L);
  38. inc(P2);
  39. end;
  40. if L>len then
  41. L:=Len;
  42. SetLength(Result,L);
  43. if Len>0 then
  44. Move(P^,Result[1],L*2);
  45. end;
  46. {$ENDIF}
  47. var
  48. re : ppcre2_code;
  49. {$IFNDEF USE_WIDESTRING}
  50. ptrn : AnsiString;
  51. subj : AnsiString;
  52. groupname : AnsiString;
  53. {$ELSE}
  54. ptrn : UnicodeString;
  55. subj : UnicodeString;
  56. groupname : UnicodeString;
  57. {$ENDIF}
  58. pattern : PCRE2_SPTR; (* PCRE2_SPTR is a pointer to unsigned code units of *)
  59. subject : PCRE2_SPTR; (* the appropriate width (in this case, 8 bits). *)
  60. name_table : PCRE2_SPTR;
  61. utf8,
  62. crlf_is_newline,
  63. find_all : Boolean;
  64. errornumber,
  65. i,n,matchlen,
  66. rc : cint;
  67. newline,
  68. name_entry_size,
  69. namecount,
  70. options,
  71. option_bits : cuint32 ;
  72. erroroffset : PCRE2_SIZE;
  73. ovector : ^PCRE2_SIZE;
  74. pattern_length,
  75. subject_length : PCRE2_SIZE;
  76. match_data : ppcre2_match_data;
  77. buffer : Array[0..255] of ansichar;
  78. substring_start : PCRE2_SPTR;
  79. substring_length : PCRE2_SIZE;
  80. tabptr: PCRE2_SPTR ;
  81. start_offset : PCRE2_SIZE;
  82. startchar : PCRE2_SIZE ;
  83. begin
  84. (*
  85. ***************************************************************************
  86. * First, sort out the command line. There is only one possible option at *
  87. * the moment, "-g" to request repeated matching to find all occurrences, *
  88. * like Perl's /g option. We set the variable find_all to a non-zero value *
  89. * if the -g option is present. *
  90. ***************************************************************************
  91. *)
  92. find_all:=False;
  93. I:=1;
  94. While I<=ParamCount do
  95. begin
  96. if (ParamStr(i)='-g') then
  97. find_all:=True
  98. else if (ParamStr(i)[1] = '-') then
  99. begin
  100. Writeln('Unrecognised option: ', paramstr(i));
  101. halt(1);
  102. end
  103. else
  104. Break;
  105. Inc(I);
  106. end;
  107. (*
  108. After the options, we require exactly two arguments, which are the pattern,
  109. and the subject string.
  110. *)
  111. if ((ParamCount-i+1)<>2) then
  112. begin
  113. Writeln('Exactly two arguments required: a regex and a subject string');
  114. Halt(1);
  115. end;
  116. (*
  117. Pattern and subject are char arguments, so they can be straightforwardly
  118. cast to PCRE2_SPTR because we are working in 8-bit code units. The subject
  119. length is cast to PCRE2_SIZE for completeness, though PCRE2_SIZE is in fact
  120. defined to be size_t.
  121. *)
  122. ptrn:=ParamStr(I);
  123. subj:=ParamStr(I+1);
  124. {$IFNDEF USE_WIDESTRING}
  125. pattern:=PAnsiChar(ptrn);
  126. subject:=PAnsiChar(Subj);
  127. {$ELSE}
  128. pattern:=PUnicodeChar(ptrn);
  129. subject:=PUnicodeChar(Subj);
  130. {$ENDIF}
  131. pattern_length:=length(pattern);
  132. subject_length:=Length(subject);
  133. (*
  134. **************************************************************************
  135. * Now we are going to compile the regular expression pattern, and handle *
  136. * any errors that are detected. *
  137. **************************************************************************
  138. *)
  139. {$IFDEF USE_WIDESTRING}
  140. re:=pcre2_compile_w(
  141. {$ELSE}
  142. re:=pcre2_compile(
  143. {$ENDIF}
  144. pattern, (* the pattern *)
  145. pattern_length, (* Pattern-length *)
  146. 0, (* default options *)
  147. @errornumber, (* for error number *)
  148. @erroroffset, (* for error offset *)
  149. Nil); (* use default compile context *)
  150. (*
  151. Compilation failed: print the error message and exit.
  152. *)
  153. if (re=Nil) then
  154. begin
  155. pcre2_get_error_message(errornumber, @buffer, sizeof(buffer));
  156. Writeln('PCRE2 compilation failed at offset ',erroroffset,': ',buffer);
  157. halt(1)
  158. end;
  159. (*
  160. **************************************************************************
  161. * If the compilation succeeded, we call PCRE2 again, in order to do a *
  162. * pattern match against the subject string. This does just ONE match. If *
  163. * further matching is needed, it will be done below. Before running the *
  164. * match we must set up a match_data block for holding the result. Using *
  165. * pcre2_match_data_create_from_pattern() ensures that the block is *
  166. * exactly the right size for the number of capturing parentheses in the *
  167. * pattern. If you need to know the actual size of a match_data block as *
  168. * a number of bytes, you can find it like this: *
  169. * *
  170. * PCRE2_SIZE match_data_size = pcre2_get_match_data_size(match_data); *
  171. **************************************************************************
  172. *)
  173. match_data := pcre2_match_data_create_from_pattern(re, Nil);
  174. (*
  175. Now run the match.
  176. *)
  177. {$IFDEF USE_WIDESTRING}
  178. rc := pcre2_match_w(
  179. {$ELSE}
  180. rc := pcre2_match(
  181. {$ENDIF}
  182. re, (* the compiled pattern *)
  183. subject, (* the subject string *)
  184. subject_length, (* the length of the subject *)
  185. 0, (* start at offset 0 in the subject *)
  186. 0, (* default options *)
  187. match_data, (* block for storing the result *)
  188. Nil); (* use default match context *)
  189. (*
  190. Matching failed: handle error cases
  191. *)
  192. if (rc < 0) then
  193. begin
  194. Case rc of
  195. PCRE2_ERROR_NOMATCH: Writeln('No match');
  196. else
  197. Writeln('Matching error ', rc);
  198. end;
  199. pcre2_match_data_free(match_data); (* Release memory used for the match *)
  200. pcre2_code_free(re); (* data and the compiled pattern. *)
  201. Halt(1);
  202. end;
  203. (*
  204. Match succeeded. Get a pointer to the output vector, where string offsets
  205. are stored.
  206. *)
  207. ovector := pcre2_get_ovector_pointer(match_data);
  208. Writeln('Match succeeded at offset ', integer(ovector[0]));
  209. (*
  210. **************************************************************************
  211. * We have found the first match within the subject string. If the output *
  212. * vector wasn't big enough, say so. Then output any substrings that were *
  213. * captured. *
  214. **************************************************************************
  215. *)
  216. (*
  217. The output vector wasn't big enough. This should not happen, because we used
  218. pcre2_match_data_create_from_pattern() above.
  219. *)
  220. if (rc = 0) then
  221. Writeln('ovector was not big enough for all the captured substrings');
  222. (*
  223. Since release 10.38 PCRE2 has locked out the use of \K in lookaround
  224. assertions. However, there is an option to re-enable the old behaviour. If that
  225. is set, it is possible to run patterns such as /(?=.\K)/ that use \K in an
  226. assertion to set the start of a match later than its end. In this demonstration
  227. program, we show how to detect this case, but it shouldn't arise because the
  228. option is never set.
  229. *)
  230. if (ovector[0] > ovector[1]) then
  231. begin
  232. i:=integer(ovector[0] - ovector[1]);
  233. Writeln('\K was used in an assertion to set the match start after its end.',
  234. 'From end to start the match was:', GetStrLen(subject+ovector[1],i));
  235. Writeln('Run abandoned');
  236. pcre2_match_data_free(match_data);
  237. pcre2_code_free(re);
  238. Halt(1);
  239. end;
  240. (*
  241. Show substrings stored in the output vector by number. Obviously, in a real
  242. application you might want to do things other than print them.
  243. *)
  244. for i:=0 to rc-1 do
  245. begin
  246. substring_start := subject + ovector[2*i];
  247. substring_length := ovector[2*i+1] - ovector[2*i];
  248. Writeln(i:2, ': ',GetStrLen(substring_start,substring_length));
  249. end ;
  250. (*
  251. ***************************************************************************
  252. * That concludes the basic part of this demonstration program. We have *
  253. * compiled a pattern, and performed a single match. The code that follows *
  254. * shows first how to access named substrings, and then how to code for *
  255. * repeated matches on the same subject. *
  256. ***************************************************************************
  257. *)
  258. (*
  259. See if there are any named substrings, and if so, show them by name.
  260. First we have to extract the count of named parentheses from the pattern.
  261. *)
  262. pcre2_pattern_info(
  263. re, (* the compiled pattern *)
  264. PCRE2_INFO_NAMECOUNT, (* get the number of named substrings *)
  265. @namecount); (* where to put the answer *)
  266. if (namecount = 0) then
  267. Writeln('No named substrings')
  268. else
  269. begin
  270. Writeln('Named substrings');
  271. (*
  272. Before we can access the substrings, we must extract the table for
  273. translating names to numbers, and the size of each entry in the table.
  274. *)
  275. pcre2_pattern_info(
  276. re, (* the compiled pattern *)
  277. PCRE2_INFO_NAMETABLE, (* address of the table *)
  278. @name_table); (* where to put the answer *)
  279. pcre2_pattern_info(
  280. re, (* the compiled pattern *)
  281. PCRE2_INFO_NAMEENTRYSIZE, (* size of each entry in the table *)
  282. @name_entry_size); (* where to put the answer *)
  283. (*
  284. Now we can scan the table and, for each entry, print the number, the name,
  285. and the substring itself. In the 8-bit library the number is held in two
  286. bytes, most significant first.
  287. *)
  288. tabptr := name_table;
  289. for i:=0 to namecount-1 do
  290. begin
  291. {$IFDEF USE_WIDESTRING}
  292. n:=ord(tabptr[0]);
  293. groupname:=GetStrLen((TabPtr+1),name_entry_size-2);
  294. {$ELSE}
  295. n:=(ord(tabptr[0]) shl 8) or ord(tabptr[1]);
  296. groupname:=GetStrLen((tabptr + 2),name_entry_size - 3),
  297. {$ENDIF}
  298. matchlen:=integer(ovector[2*n+1] - ovector[2*n]);
  299. writeln( '(',n,')', Groupname,' : ',
  300. GetStrLen((subject + ovector[2*n]), Matchlen));
  301. inc(tabptr, name_entry_size);
  302. end ;
  303. end ;
  304. (*
  305. **************************************************************************
  306. * If the '-g' option was given on the command line, we want to continue *
  307. * to search for additional matches in the subject string, in a similar *
  308. * way to the /g option in Perl. This turns out to be trickier than you *
  309. * might think because of the possibility of matching an empty string. *
  310. * What happens is as follows: *
  311. * *
  312. * If the previous match was NOT for an empty string, we can just start *
  313. * the next match at the end of the previous one. *
  314. * *
  315. * If the previous match WAS for an empty string, we can't do that, as it *
  316. * would lead to an infinite loop. Instead, a call of pcre2_match() is *
  317. * made with the PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED flags set. The *
  318. * first of these tells PCRE2 that an empty string at the start of the *
  319. * subject is not a valid match; other possibilities must be tried. The *
  320. * second flag restricts PCRE2 to one match attempt at the initial string *
  321. * position. If this match succeeds, an alternative to the empty string *
  322. * match has been found, and we can print it and proceed round the loop, *
  323. * advancing by the length of whatever was found. If this match does not *
  324. * succeed, we still stay in the loop, advancing by just one character. *
  325. * In UTF-8 mode, which can be set by ( *UTF) in the pattern, this may be *
  326. * more than one byte. *
  327. * *
  328. * However, there is a complication concerned with newlines. When the *
  329. * newline convention is such that CRLF is a valid newline, we must *
  330. * advance by two characters rather than one. The newline convention can *
  331. * be set in the regex by ( *CR), etc.; if not, we must find the default. *
  332. **************************************************************************
  333. *)
  334. if Not find_all then (* Check for -g *)
  335. begin
  336. pcre2_match_data_free(match_data); (* Release the memory that was used *)
  337. pcre2_code_free(re); (* for the match data and the pattern. *)
  338. Halt(0); (* Exit the program. *)
  339. end ;
  340. (*
  341. Before running the loop, check for UTF-8 and whether CRLF is a valid newline
  342. sequence. First, find the options with which the regex was compiled and extract
  343. the UTF state.
  344. *)
  345. pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, @option_bits);
  346. utf8 := ((option_bits and PCRE2_UTF) <> 0);
  347. (*
  348. Now find the newline convention and see whether CRLF is a valid newline
  349. sequence.
  350. *)
  351. pcre2_pattern_info(re, PCRE2_INFO_NEWLINE, @newline);
  352. crlf_is_newline := (newline = PCRE2_NEWLINE_ANY) or
  353. (newline = PCRE2_NEWLINE_CRLF) or
  354. (newline = PCRE2_NEWLINE_ANYCRLF);
  355. (* Loop for second and subsequent matches *)
  356. While true do
  357. begin
  358. options := 0; (* Normally no options *)
  359. start_offset := ovector[1]; (* Start at end of previous match *)
  360. (*
  361. If the previous match was for an empty string, we are finished if we are
  362. at the end of the subject. Otherwise, arrange to run another match at the
  363. same point to see if a non-empty match can be found.
  364. *)
  365. if (ovector[0] = ovector[1]) then
  366. begin
  367. if (ovector[0] = subject_length) then
  368. break;
  369. options := PCRE2_NOTEMPTY_ATSTART or PCRE2_ANCHORED;
  370. end
  371. (*
  372. If the previous match was not an empty string, there is one tricky case to
  373. consider. If a pattern contains \K within a lookbehind assertion at the
  374. start, the end of the matched string can be at the offset where the match
  375. started. Without special action, this leads to a loop that keeps on matching
  376. the same substring. We must detect this case and arrange to move the start on
  377. by one character. The pcre2_get_startchar() function returns the starting
  378. offset that was passed to pcre2_match().
  379. *)
  380. else
  381. begin
  382. startchar := pcre2_get_startchar(match_data);
  383. if (start_offset <= startchar) then
  384. begin
  385. if (startchar >= subject_length) then
  386. break; (* Reached end of subject. *)
  387. start_offset:=startchar + 1; (* Advance by one character. *)
  388. if utf8 then (* If UTF-8, it may be more *)
  389. begin (* than one code unit. *)
  390. While (start_offset < subject_length) do
  391. begin
  392. if ((Ord(subject[start_offset]) and $c0) <> $80) then
  393. break;
  394. inc(start_offset);
  395. end;
  396. end
  397. end
  398. end ;
  399. (*
  400. Run the next matching operation
  401. *)
  402. {$IFDEF USE_WIDESTRING}
  403. rc := pcre2_match_w(
  404. {$ELSE}
  405. rc := pcre2_match(
  406. {$ENDIF}
  407. re, (* the compiled pattern *)
  408. subject, (* the subject string *)
  409. subject_length, (* the length of the subject *)
  410. start_offset, (* starting offset in the subject *)
  411. options, (* options *)
  412. match_data, (* block for storing the result *)
  413. Nil); (* use default match context *)
  414. (*
  415. This time, a result of NOMATCH isn't an error. If the value in 'options'
  416. is zero, it just means we have found all possible matches, so the loop ends.
  417. Otherwise, it means we have failed to find a non-empty-string match at a
  418. point where there was a previous empty-string match. In this case, we do what
  419. Perl does: advance the matching position by one character, and continue. We
  420. do this by setting the 'end of previous match' offset, because that is picked
  421. up at the top of the loop as the point at which to start again.
  422. There are two complications: (a) When CRLF is a valid newline sequence, and
  423. the current position is just before it, advance by an extra byte. (b)
  424. Otherwise we must ensure that we skip an entire UTF character if we are in
  425. UTF mode.
  426. *)
  427. if (rc = PCRE2_ERROR_NOMATCH) then
  428. begin
  429. if (options = 0) then
  430. break; (* All matches found *)
  431. ovector[1] := start_offset + 1; (* Advance one code unit *)
  432. if (crlf_is_newline) and (* If CRLF is a newline & *)
  433. (start_offset < subject_length - 1) and (* we are at CRLF, *)
  434. (subject[start_offset] = #13) and
  435. (subject[start_offset + 1] = #10) then
  436. inc(ovector[1]) (* Advance by one more. *)
  437. else if (utf8) then (* Otherwise, ensure we *)
  438. begin (* advance a whole UTF-8 *)
  439. while (ovector[1] < subject_length) do (* character. *)
  440. begin
  441. if ((Ord(subject[ovector[1]]) and $c0) <> $80) then
  442. break;
  443. inc(ovector[1]);
  444. end;
  445. end;
  446. continue; (* Go round the loop again *)
  447. end;
  448. (*
  449. Other matching errors are not recoverable.
  450. *)
  451. if (rc < 0) then
  452. begin
  453. Writeln('Matching error %d', rc);
  454. pcre2_match_data_free(match_data);
  455. pcre2_code_free(re);
  456. Halt(1);
  457. end;
  458. (*
  459. Match succeeded
  460. *)
  461. Writeln('Match succeeded again at offset ', integer (ovector[0]));
  462. (*
  463. The match succeeded, but the output vector wasn't big enough. This
  464. should not happen.
  465. *)
  466. if (rc = 0) then
  467. Writeln('ovector was not big enough for all the captured substrings');
  468. (*
  469. We must guard against patterns such as /(?=.\K)/ that use \K in an
  470. assertion to set the start of a match later than its end. In this
  471. demonstration program, we just detect this case and give up.
  472. *)
  473. if (ovector[0] > ovector[1]) then
  474. begin
  475. matchlen:=Integer(ovector[0] - ovector[1]);
  476. writeln('\K was used in an assertion to set the match start after its end.');
  477. Writeln('From end to start the match was: ', GetStrLen((subject + ovector[1]),matchlen));
  478. writeln('Run abandoned');
  479. pcre2_match_data_free(match_data);
  480. pcre2_code_free(re);
  481. Halt(1);
  482. end ;
  483. (*
  484. As before, show substrings stored in the output vector by number, and then
  485. also any named substrings.
  486. *)
  487. for i := 0 to rc-1 do
  488. begin
  489. substring_start:=subject + ovector[2*i];
  490. substring_length:=ovector[2*i+1] - ovector[2*i];
  491. Writeln(i,': ',GetStrLen(substring_start,substring_length));
  492. end;
  493. if (namecount = 0) then
  494. Writeln('No named substrings')
  495. else
  496. begin
  497. Writeln('Named substrings');
  498. for i:=0 to namecount-1 do
  499. begin
  500. {$IFDEF USE_WIDESTRING}
  501. n:=ord(tabptr[0]);
  502. groupname:=GetStrLen((TabPtr+1),name_entry_size-2);
  503. {$ELSE}
  504. n:=(ord(tabptr[0]) shl 8) or ord(tabptr[1]);
  505. groupname:=GetStrLen((tabptr + 2),name_entry_size - 3),
  506. {$ENDIF}
  507. matchlen:=integer(ovector[2*n+1] - ovector[2*n]);
  508. writeln( '(',n,')', Groupname,' : ', GetStrLen((subject + ovector[2*n]), Matchlen));
  509. tabptr := tabptr+name_entry_size;
  510. end ;
  511. end;
  512. end ;
  513. (*
  514. End of loop to find second and subsequent matches
  515. *)
  516. Writeln('');
  517. pcre2_match_data_free(match_data);
  518. pcre2_code_free(re);
  519. end.