github的一些开源项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

518 lines
20 KiB

  1. <html>
  2. <head>
  3. <title>pcre2demo specification</title>
  4. </head>
  5. <body bgcolor="#FFFFFF" text="#00005A" link="#0066FF" alink="#3399FF" vlink="#2222BB">
  6. <h1>pcre2demo man page</h1>
  7. <p>
  8. Return to the <a href="index.html">PCRE2 index page</a>.
  9. </p>
  10. <p>
  11. This page is part of the PCRE2 HTML documentation. It was generated
  12. automatically from the original man page. If there is any nonsense in it,
  13. please consult the man page, in case the conversion went wrong.
  14. <br>
  15. <br><b>
  16. SOURCE CODE
  17. </b><br>
  18. <PRE>
  19. /*************************************************
  20. * PCRE2 DEMONSTRATION PROGRAM *
  21. *************************************************/
  22. /* This is a demonstration program to illustrate a straightforward way of
  23. using the PCRE2 regular expression library from a C program. See the
  24. pcre2sample documentation for a short discussion ("man pcre2sample" if you have
  25. the PCRE2 man pages installed). PCRE2 is a revised API for the library, and is
  26. incompatible with the original PCRE API.
  27. There are actually three libraries, each supporting a different code unit
  28. width. This demonstration program uses the 8-bit library. The default is to
  29. process each code unit as a separate character, but if the pattern begins with
  30. "(*UTF)", both it and the subject are treated as UTF-8 strings, where
  31. characters may occupy multiple code units.
  32. In Unix-like environments, if PCRE2 is installed in your standard system
  33. libraries, you should be able to compile this program using this command:
  34. cc -Wall pcre2demo.c -lpcre2-8 -o pcre2demo
  35. If PCRE2 is not installed in a standard place, it is likely to be installed
  36. with support for the pkg-config mechanism. If you have pkg-config, you can
  37. compile this program using this command:
  38. cc -Wall pcre2demo.c `pkg-config --cflags --libs libpcre2-8` -o pcre2demo
  39. If you do not have pkg-config, you may have to use something like this:
  40. cc -Wall pcre2demo.c -I/usr/local/include -L/usr/local/lib \
  41. -R/usr/local/lib -lpcre2-8 -o pcre2demo
  42. Replace "/usr/local/include" and "/usr/local/lib" with wherever the include and
  43. library files for PCRE2 are installed on your system. Only some operating
  44. systems (Solaris is one) use the -R option.
  45. Building under Windows:
  46. If you want to statically link this program against a non-dll .a file, you must
  47. define PCRE2_STATIC before including pcre2.h, so in this environment, uncomment
  48. the following line. */
  49. /* #define PCRE2_STATIC */
  50. /* The PCRE2_CODE_UNIT_WIDTH macro must be defined before including pcre2.h.
  51. For a program that uses only one code unit width, setting it to 8, 16, or 32
  52. makes it possible to use generic function names such as pcre2_compile(). Note
  53. that just changing 8 to 16 (for example) is not sufficient to convert this
  54. program to process 16-bit characters. Even in a fully 16-bit environment, where
  55. string-handling functions such as strcmp() and printf() work with 16-bit
  56. characters, the code for handling the table of named substrings will still need
  57. to be modified. */
  58. #define PCRE2_CODE_UNIT_WIDTH 8
  59. #include &lt;stdio.h&gt;
  60. #include &lt;string.h&gt;
  61. #include &lt;pcre2.h&gt;
  62. /**************************************************************************
  63. * Here is the program. The API includes the concept of "contexts" for *
  64. * setting up unusual interface requirements for compiling and matching, *
  65. * such as custom memory managers and non-standard newline definitions. *
  66. * This program does not do any of this, so it makes no use of contexts, *
  67. * always passing NULL where a context could be given. *
  68. **************************************************************************/
  69. int main(int argc, char **argv)
  70. {
  71. pcre2_code *re;
  72. PCRE2_SPTR pattern; /* PCRE2_SPTR is a pointer to unsigned code units of */
  73. PCRE2_SPTR subject; /* the appropriate width (in this case, 8 bits). */
  74. PCRE2_SPTR name_table;
  75. int crlf_is_newline;
  76. int errornumber;
  77. int find_all;
  78. int i;
  79. int rc;
  80. int utf8;
  81. uint32_t option_bits;
  82. uint32_t namecount;
  83. uint32_t name_entry_size;
  84. uint32_t newline;
  85. PCRE2_SIZE erroroffset;
  86. PCRE2_SIZE *ovector;
  87. PCRE2_SIZE subject_length;
  88. pcre2_match_data *match_data;
  89. /**************************************************************************
  90. * First, sort out the command line. There is only one possible option at *
  91. * the moment, "-g" to request repeated matching to find all occurrences, *
  92. * like Perl's /g option. We set the variable find_all to a non-zero value *
  93. * if the -g option is present. *
  94. **************************************************************************/
  95. find_all = 0;
  96. for (i = 1; i &lt; argc; i++)
  97. {
  98. if (strcmp(argv[i], "-g") == 0) find_all = 1;
  99. else if (argv[i][0] == '-')
  100. {
  101. printf("Unrecognised option %s\n", argv[i]);
  102. return 1;
  103. }
  104. else break;
  105. }
  106. /* After the options, we require exactly two arguments, which are the pattern,
  107. and the subject string. */
  108. if (argc - i != 2)
  109. {
  110. printf("Exactly two arguments required: a regex and a subject string\n");
  111. return 1;
  112. }
  113. /* Pattern and subject are char arguments, so they can be straightforwardly
  114. cast to PCRE2_SPTR because we are working in 8-bit code units. The subject
  115. length is cast to PCRE2_SIZE for completeness, though PCRE2_SIZE is in fact
  116. defined to be size_t. */
  117. pattern = (PCRE2_SPTR)argv[i];
  118. subject = (PCRE2_SPTR)argv[i+1];
  119. subject_length = (PCRE2_SIZE)strlen((char *)subject);
  120. /*************************************************************************
  121. * Now we are going to compile the regular expression pattern, and handle *
  122. * any errors that are detected. *
  123. *************************************************************************/
  124. re = pcre2_compile(
  125. pattern, /* the pattern */
  126. PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  127. 0, /* default options */
  128. &amp;errornumber, /* for error number */
  129. &amp;erroroffset, /* for error offset */
  130. NULL); /* use default compile context */
  131. /* Compilation failed: print the error message and exit. */
  132. if (re == NULL)
  133. {
  134. PCRE2_UCHAR buffer[256];
  135. pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  136. printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,
  137. buffer);
  138. return 1;
  139. }
  140. /*************************************************************************
  141. * If the compilation succeeded, we call PCRE2 again, in order to do a *
  142. * pattern match against the subject string. This does just ONE match. If *
  143. * further matching is needed, it will be done below. Before running the *
  144. * match we must set up a match_data block for holding the result. Using *
  145. * pcre2_match_data_create_from_pattern() ensures that the block is *
  146. * exactly the right size for the number of capturing parentheses in the *
  147. * pattern. If you need to know the actual size of a match_data block as *
  148. * a number of bytes, you can find it like this: *
  149. * *
  150. * PCRE2_SIZE match_data_size = pcre2_get_match_data_size(match_data); *
  151. *************************************************************************/
  152. match_data = pcre2_match_data_create_from_pattern(re, NULL);
  153. /* Now run the match. */
  154. rc = pcre2_match(
  155. re, /* the compiled pattern */
  156. subject, /* the subject string */
  157. subject_length, /* the length of the subject */
  158. 0, /* start at offset 0 in the subject */
  159. 0, /* default options */
  160. match_data, /* block for storing the result */
  161. NULL); /* use default match context */
  162. /* Matching failed: handle error cases */
  163. if (rc &lt; 0)
  164. {
  165. switch(rc)
  166. {
  167. case PCRE2_ERROR_NOMATCH: printf("No match\n"); break;
  168. /*
  169. Handle other special cases if you like
  170. */
  171. default: printf("Matching error %d\n", rc); break;
  172. }
  173. pcre2_match_data_free(match_data); /* Release memory used for the match */
  174. pcre2_code_free(re); /* data and the compiled pattern. */
  175. return 1;
  176. }
  177. /* Match succeeded. Get a pointer to the output vector, where string offsets
  178. are stored. */
  179. ovector = pcre2_get_ovector_pointer(match_data);
  180. printf("Match succeeded at offset %d\n", (int)ovector[0]);
  181. /*************************************************************************
  182. * We have found the first match within the subject string. If the output *
  183. * vector wasn't big enough, say so. Then output any substrings that were *
  184. * captured. *
  185. *************************************************************************/
  186. /* The output vector wasn't big enough. This should not happen, because we used
  187. pcre2_match_data_create_from_pattern() above. */
  188. if (rc == 0)
  189. printf("ovector was not big enough for all the captured substrings\n");
  190. /* Since release 10.38 PCRE2 has locked out the use of \K in lookaround
  191. assertions. However, there is an option to re-enable the old behaviour. If that
  192. is set, it is possible to run patterns such as /(?=.\K)/ that use \K in an
  193. assertion to set the start of a match later than its end. In this demonstration
  194. program, we show how to detect this case, but it shouldn't arise because the
  195. option is never set. */
  196. if (ovector[0] &gt; ovector[1])
  197. {
  198. printf("\\K was used in an assertion to set the match start after its end.\n"
  199. "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
  200. (char *)(subject + ovector[1]));
  201. printf("Run abandoned\n");
  202. pcre2_match_data_free(match_data);
  203. pcre2_code_free(re);
  204. return 1;
  205. }
  206. /* Show substrings stored in the output vector by number. Obviously, in a real
  207. application you might want to do things other than print them. */
  208. for (i = 0; i &lt; rc; i++)
  209. {
  210. PCRE2_SPTR substring_start = subject + ovector[2*i];
  211. PCRE2_SIZE substring_length = ovector[2*i+1] - ovector[2*i];
  212. printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  213. }
  214. /**************************************************************************
  215. * That concludes the basic part of this demonstration program. We have *
  216. * compiled a pattern, and performed a single match. The code that follows *
  217. * shows first how to access named substrings, and then how to code for *
  218. * repeated matches on the same subject. *
  219. **************************************************************************/
  220. /* See if there are any named substrings, and if so, show them by name. First
  221. we have to extract the count of named parentheses from the pattern. */
  222. (void)pcre2_pattern_info(
  223. re, /* the compiled pattern */
  224. PCRE2_INFO_NAMECOUNT, /* get the number of named substrings */
  225. &amp;namecount); /* where to put the answer */
  226. if (namecount == 0) printf("No named substrings\n"); else
  227. {
  228. PCRE2_SPTR tabptr;
  229. printf("Named substrings\n");
  230. /* Before we can access the substrings, we must extract the table for
  231. translating names to numbers, and the size of each entry in the table. */
  232. (void)pcre2_pattern_info(
  233. re, /* the compiled pattern */
  234. PCRE2_INFO_NAMETABLE, /* address of the table */
  235. &amp;name_table); /* where to put the answer */
  236. (void)pcre2_pattern_info(
  237. re, /* the compiled pattern */
  238. PCRE2_INFO_NAMEENTRYSIZE, /* size of each entry in the table */
  239. &amp;name_entry_size); /* where to put the answer */
  240. /* Now we can scan the table and, for each entry, print the number, the name,
  241. and the substring itself. In the 8-bit library the number is held in two
  242. bytes, most significant first. */
  243. tabptr = name_table;
  244. for (i = 0; i &lt; namecount; i++)
  245. {
  246. int n = (tabptr[0] &lt;&lt; 8) | tabptr[1];
  247. printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
  248. (int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]);
  249. tabptr += name_entry_size;
  250. }
  251. }
  252. /*************************************************************************
  253. * If the "-g" option was given on the command line, we want to continue *
  254. * to search for additional matches in the subject string, in a similar *
  255. * way to the /g option in Perl. This turns out to be trickier than you *
  256. * might think because of the possibility of matching an empty string. *
  257. * What happens is as follows: *
  258. * *
  259. * If the previous match was NOT for an empty string, we can just start *
  260. * the next match at the end of the previous one. *
  261. * *
  262. * If the previous match WAS for an empty string, we can't do that, as it *
  263. * would lead to an infinite loop. Instead, a call of pcre2_match() is *
  264. * made with the PCRE2_NOTEMPTY_ATSTART and PCRE2_ANCHORED flags set. The *
  265. * first of these tells PCRE2 that an empty string at the start of the *
  266. * subject is not a valid match; other possibilities must be tried. The *
  267. * second flag restricts PCRE2 to one match attempt at the initial string *
  268. * position. If this match succeeds, an alternative to the empty string *
  269. * match has been found, and we can print it and proceed round the loop, *
  270. * advancing by the length of whatever was found. If this match does not *
  271. * succeed, we still stay in the loop, advancing by just one character. *
  272. * In UTF-8 mode, which can be set by (*UTF) in the pattern, this may be *
  273. * more than one byte. *
  274. * *
  275. * However, there is a complication concerned with newlines. When the *
  276. * newline convention is such that CRLF is a valid newline, we must *
  277. * advance by two characters rather than one. The newline convention can *
  278. * be set in the regex by (*CR), etc.; if not, we must find the default. *
  279. *************************************************************************/
  280. if (!find_all) /* Check for -g */
  281. {
  282. pcre2_match_data_free(match_data); /* Release the memory that was used */
  283. pcre2_code_free(re); /* for the match data and the pattern. */
  284. return 0; /* Exit the program. */
  285. }
  286. /* Before running the loop, check for UTF-8 and whether CRLF is a valid newline
  287. sequence. First, find the options with which the regex was compiled and extract
  288. the UTF state. */
  289. (void)pcre2_pattern_info(re, PCRE2_INFO_ALLOPTIONS, &amp;option_bits);
  290. utf8 = (option_bits &amp; PCRE2_UTF) != 0;
  291. /* Now find the newline convention and see whether CRLF is a valid newline
  292. sequence. */
  293. (void)pcre2_pattern_info(re, PCRE2_INFO_NEWLINE, &amp;newline);
  294. crlf_is_newline = newline == PCRE2_NEWLINE_ANY ||
  295. newline == PCRE2_NEWLINE_CRLF ||
  296. newline == PCRE2_NEWLINE_ANYCRLF;
  297. /* Loop for second and subsequent matches */
  298. for (;;)
  299. {
  300. uint32_t options = 0; /* Normally no options */
  301. PCRE2_SIZE start_offset = ovector[1]; /* Start at end of previous match */
  302. /* If the previous match was for an empty string, we are finished if we are
  303. at the end of the subject. Otherwise, arrange to run another match at the
  304. same point to see if a non-empty match can be found. */
  305. if (ovector[0] == ovector[1])
  306. {
  307. if (ovector[0] == subject_length) break;
  308. options = PCRE2_NOTEMPTY_ATSTART | PCRE2_ANCHORED;
  309. }
  310. /* If the previous match was not an empty string, there is one tricky case to
  311. consider. If a pattern contains \K within a lookbehind assertion at the
  312. start, the end of the matched string can be at the offset where the match
  313. started. Without special action, this leads to a loop that keeps on matching
  314. the same substring. We must detect this case and arrange to move the start on
  315. by one character. The pcre2_get_startchar() function returns the starting
  316. offset that was passed to pcre2_match(). */
  317. else
  318. {
  319. PCRE2_SIZE startchar = pcre2_get_startchar(match_data);
  320. if (start_offset &lt;= startchar)
  321. {
  322. if (startchar &gt;= subject_length) break; /* Reached end of subject. */
  323. start_offset = startchar + 1; /* Advance by one character. */
  324. if (utf8) /* If UTF-8, it may be more */
  325. { /* than one code unit. */
  326. for (; start_offset &lt; subject_length; start_offset++)
  327. if ((subject[start_offset] &amp; 0xc0) != 0x80) break;
  328. }
  329. }
  330. }
  331. /* Run the next matching operation */
  332. rc = pcre2_match(
  333. re, /* the compiled pattern */
  334. subject, /* the subject string */
  335. subject_length, /* the length of the subject */
  336. start_offset, /* starting offset in the subject */
  337. options, /* options */
  338. match_data, /* block for storing the result */
  339. NULL); /* use default match context */
  340. /* This time, a result of NOMATCH isn't an error. If the value in "options"
  341. is zero, it just means we have found all possible matches, so the loop ends.
  342. Otherwise, it means we have failed to find a non-empty-string match at a
  343. point where there was a previous empty-string match. In this case, we do what
  344. Perl does: advance the matching position by one character, and continue. We
  345. do this by setting the "end of previous match" offset, because that is picked
  346. up at the top of the loop as the point at which to start again.
  347. There are two complications: (a) When CRLF is a valid newline sequence, and
  348. the current position is just before it, advance by an extra byte. (b)
  349. Otherwise we must ensure that we skip an entire UTF character if we are in
  350. UTF mode. */
  351. if (rc == PCRE2_ERROR_NOMATCH)
  352. {
  353. if (options == 0) break; /* All matches found */
  354. ovector[1] = start_offset + 1; /* Advance one code unit */
  355. if (crlf_is_newline &amp;&amp; /* If CRLF is a newline &amp; */
  356. start_offset &lt; subject_length - 1 &amp;&amp; /* we are at CRLF, */
  357. subject[start_offset] == '\r' &amp;&amp;
  358. subject[start_offset + 1] == '\n')
  359. ovector[1] += 1; /* Advance by one more. */
  360. else if (utf8) /* Otherwise, ensure we */
  361. { /* advance a whole UTF-8 */
  362. while (ovector[1] &lt; subject_length) /* character. */
  363. {
  364. if ((subject[ovector[1]] &amp; 0xc0) != 0x80) break;
  365. ovector[1] += 1;
  366. }
  367. }
  368. continue; /* Go round the loop again */
  369. }
  370. /* Other matching errors are not recoverable. */
  371. if (rc &lt; 0)
  372. {
  373. printf("Matching error %d\n", rc);
  374. pcre2_match_data_free(match_data);
  375. pcre2_code_free(re);
  376. return 1;
  377. }
  378. /* Match succeeded */
  379. printf("\nMatch succeeded again at offset %d\n", (int)ovector[0]);
  380. /* The match succeeded, but the output vector wasn't big enough. This
  381. should not happen. */
  382. if (rc == 0)
  383. printf("ovector was not big enough for all the captured substrings\n");
  384. /* We must guard against patterns such as /(?=.\K)/ that use \K in an
  385. assertion to set the start of a match later than its end. In this
  386. demonstration program, we just detect this case and give up. */
  387. if (ovector[0] &gt; ovector[1])
  388. {
  389. printf("\\K was used in an assertion to set the match start after its end.\n"
  390. "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
  391. (char *)(subject + ovector[1]));
  392. printf("Run abandoned\n");
  393. pcre2_match_data_free(match_data);
  394. pcre2_code_free(re);
  395. return 1;
  396. }
  397. /* As before, show substrings stored in the output vector by number, and then
  398. also any named substrings. */
  399. for (i = 0; i &lt; rc; i++)
  400. {
  401. PCRE2_SPTR substring_start = subject + ovector[2*i];
  402. size_t substring_length = ovector[2*i+1] - ovector[2*i];
  403. printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  404. }
  405. if (namecount == 0) printf("No named substrings\n"); else
  406. {
  407. PCRE2_SPTR tabptr = name_table;
  408. printf("Named substrings\n");
  409. for (i = 0; i &lt; namecount; i++)
  410. {
  411. int n = (tabptr[0] &lt;&lt; 8) | tabptr[1];
  412. printf("(%d) %*s: %.*s\n", n, name_entry_size - 3, tabptr + 2,
  413. (int)(ovector[2*n+1] - ovector[2*n]), subject + ovector[2*n]);
  414. tabptr += name_entry_size;
  415. }
  416. }
  417. } /* End of loop to find second and subsequent matches */
  418. printf("\n");
  419. pcre2_match_data_free(match_data);
  420. pcre2_code_free(re);
  421. return 0;
  422. }
  423. /* End of pcre2demo.c */
  424. <p>
  425. Return to the <a href="index.html">PCRE2 index page</a>.
  426. </p>