Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

gregex.c 82KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783
  1. /* GRegex -- regular expression API wrapper around PCRE.
  2. *
  3. * Copyright (C) 1999, 2000 Scott Wimer
  4. * Copyright (C) 2004, Matthias Clasen <mclasen@redhat.com>
  5. * Copyright (C) 2005 - 2007, Marco Barisione <marco@barisione.org>
  6. *
  7. * This library is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * This library is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this library; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #include <string.h>
  23. #include "glib.h"
  24. #include "gregex.h"
  25. #include <pcre.h>
  26. /* PCRE 7.3 does not contain the definition of PCRE_ERROR_NULLWSLIMIT */
  27. #ifndef PCRE_ERROR_NULLWSLIMIT
  28. #define PCRE_ERROR_NULLWSLIMIT (-22)
  29. #endif
  30. /* Mask of all the possible values for GRegexCompileFlags. */
  31. #define G_REGEX_COMPILE_MASK (G_REGEX_CASELESS | \
  32. G_REGEX_MULTILINE | \
  33. G_REGEX_DOTALL | \
  34. G_REGEX_EXTENDED | \
  35. G_REGEX_ANCHORED | \
  36. G_REGEX_DOLLAR_ENDONLY | \
  37. G_REGEX_UNGREEDY | \
  38. G_REGEX_RAW | \
  39. G_REGEX_NO_AUTO_CAPTURE | \
  40. G_REGEX_OPTIMIZE | \
  41. G_REGEX_DUPNAMES | \
  42. G_REGEX_NEWLINE_CR | \
  43. G_REGEX_NEWLINE_LF | \
  44. G_REGEX_NEWLINE_CRLF)
  45. /* Mask of all the possible values for GRegexMatchFlags. */
  46. #define G_REGEX_MATCH_MASK (G_REGEX_MATCH_ANCHORED | \
  47. G_REGEX_MATCH_NOTBOL | \
  48. G_REGEX_MATCH_NOTEOL | \
  49. G_REGEX_MATCH_NOTEMPTY | \
  50. G_REGEX_MATCH_PARTIAL | \
  51. G_REGEX_MATCH_NEWLINE_CR | \
  52. G_REGEX_MATCH_NEWLINE_LF | \
  53. G_REGEX_MATCH_NEWLINE_CRLF | \
  54. G_REGEX_MATCH_NEWLINE_ANY)
  55. /* if the string is in UTF-8 use g_utf8_ functions, else use
  56. * use just +/- 1. */
  57. #define NEXT_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
  58. g_utf8_next_char (s) : \
  59. ((s) + 1))
  60. #define PREV_CHAR(re, s) (((re)->compile_opts & PCRE_UTF8) ? \
  61. g_utf8_prev_char (s) : \
  62. ((s) - 1))
  63. struct _GMatchInfo
  64. {
  65. GRegex *regex; /* the regex */
  66. GRegexMatchFlags match_opts; /* options used at match time on the regex */
  67. gint matches; /* number of matching sub patterns */
  68. gint pos; /* position in the string where last match left off */
  69. gint *offsets; /* array of offsets paired 0,1 ; 2,3 ; 3,4 etc */
  70. gint n_offsets; /* number of offsets */
  71. gint *workspace; /* workspace for pcre_dfa_exec() */
  72. gint n_workspace; /* number of workspace elements */
  73. const gchar *string; /* string passed to the match function */
  74. gssize string_len; /* length of string */
  75. };
  76. struct _GRegex
  77. {
  78. volatile gint ref_count; /* the ref count for the immutable part */
  79. gchar *pattern; /* the pattern */
  80. pcre *pcre_re; /* compiled form of the pattern */
  81. GRegexCompileFlags compile_opts; /* options used at compile time on the pattern */
  82. GRegexMatchFlags match_opts; /* options used at match time on the regex */
  83. pcre_extra *extra; /* data stored when G_REGEX_OPTIMIZE is used */
  84. };
  85. /* TRUE if ret is an error code, FALSE otherwise. */
  86. #define IS_PCRE_ERROR(ret) ((ret) < PCRE_ERROR_NOMATCH && (ret) != PCRE_ERROR_PARTIAL)
  87. typedef struct _InterpolationData InterpolationData;
  88. static gboolean interpolation_list_needs_match (GList *list);
  89. static gboolean interpolate_replacement (const GMatchInfo *match_info,
  90. GString *result,
  91. gpointer data);
  92. static GList *split_replacement (const gchar *replacement,
  93. GError **error);
  94. static void free_interpolation_data (InterpolationData *data);
  95. static const gchar *
  96. match_error (gint errcode)
  97. {
  98. switch (errcode)
  99. {
  100. case PCRE_ERROR_NOMATCH:
  101. /* not an error */
  102. break;
  103. case PCRE_ERROR_NULL:
  104. /* NULL argument, this should not happen in GRegex */
  105. g_warning ("A NULL argument was passed to PCRE");
  106. break;
  107. case PCRE_ERROR_BADOPTION:
  108. return "bad options";
  109. case PCRE_ERROR_BADMAGIC:
  110. return "corrupted object";
  111. case PCRE_ERROR_NOMEMORY:
  112. return "out of memory";
  113. case PCRE_ERROR_NOSUBSTRING:
  114. /* not used by pcre_exec() */
  115. break;
  116. case PCRE_ERROR_MATCHLIMIT:
  117. return "backtracking limit reached";
  118. case PCRE_ERROR_CALLOUT:
  119. /* callouts are not implemented */
  120. break;
  121. case PCRE_ERROR_BADUTF8:
  122. case PCRE_ERROR_BADUTF8_OFFSET:
  123. /* we do not check if strings are valid */
  124. break;
  125. case PCRE_ERROR_PARTIAL:
  126. /* not an error */
  127. break;
  128. case PCRE_ERROR_BADPARTIAL:
  129. return "the pattern contains items not supported for partial matching";
  130. case PCRE_ERROR_INTERNAL:
  131. return "internal error";
  132. case PCRE_ERROR_BADCOUNT:
  133. /* negative ovecsize, this should not happen in GRegex */
  134. g_warning ("A negative ovecsize was passed to PCRE");
  135. break;
  136. case PCRE_ERROR_DFA_UITEM:
  137. return "the pattern contains items not supported for partial matching";
  138. case PCRE_ERROR_DFA_UCOND:
  139. return "back references as conditions are not supported for partial matching";
  140. case PCRE_ERROR_DFA_UMLIMIT:
  141. /* the match_field field is not used in GRegex */
  142. break;
  143. case PCRE_ERROR_DFA_WSSIZE:
  144. /* handled expanding the workspace */
  145. break;
  146. case PCRE_ERROR_DFA_RECURSE:
  147. case PCRE_ERROR_RECURSIONLIMIT:
  148. return "recursion limit reached";
  149. case PCRE_ERROR_NULLWSLIMIT:
  150. return "workspace limit for empty substrings reached";
  151. default:
  152. break;
  153. }
  154. return "unknown error";
  155. }
  156. static void
  157. translate_compile_error (gint *errcode, const gchar **errmsg)
  158. {
  159. /* Compile errors are created adding 100 to the error code returned
  160. * by PCRE.
  161. * If errcode is known we put the translatable error message in
  162. * erromsg. If errcode is unknown we put the generic
  163. * G_REGEX_ERROR_COMPILE error code in errcode and keep the
  164. * untranslated error message returned by PCRE.
  165. * Note that there can be more PCRE errors with the same GRegexError
  166. * and that some PCRE errors are useless for us.
  167. */
  168. *errcode += 100;
  169. switch (*errcode)
  170. {
  171. case G_REGEX_ERROR_STRAY_BACKSLASH:
  172. *errmsg = "\\ at end of pattern";
  173. break;
  174. case G_REGEX_ERROR_MISSING_CONTROL_CHAR:
  175. *errmsg = "\\c at end of pattern";
  176. break;
  177. case G_REGEX_ERROR_UNRECOGNIZED_ESCAPE:
  178. *errmsg = "unrecognized character follows \\";
  179. break;
  180. case 137:
  181. /* A number of Perl escapes are not handled by PCRE.
  182. * Therefore it explicitly raises ERR37.
  183. */
  184. *errcode = G_REGEX_ERROR_UNRECOGNIZED_ESCAPE;
  185. *errmsg = "case-changing escapes (\\l, \\L, \\u, \\U) are not allowed here";
  186. break;
  187. case G_REGEX_ERROR_QUANTIFIERS_OUT_OF_ORDER:
  188. *errmsg = "numbers out of order in {} quantifier";
  189. break;
  190. case G_REGEX_ERROR_QUANTIFIER_TOO_BIG:
  191. *errmsg = "number too big in {} quantifier";
  192. break;
  193. case G_REGEX_ERROR_UNTERMINATED_CHARACTER_CLASS:
  194. *errmsg = "missing terminating ] for character class";
  195. break;
  196. case G_REGEX_ERROR_INVALID_ESCAPE_IN_CHARACTER_CLASS:
  197. *errmsg = "invalid escape sequence in character class";
  198. break;
  199. case G_REGEX_ERROR_RANGE_OUT_OF_ORDER:
  200. *errmsg = "range out of order in character class";
  201. break;
  202. case G_REGEX_ERROR_NOTHING_TO_REPEAT:
  203. *errmsg = "nothing to repeat";
  204. break;
  205. case G_REGEX_ERROR_UNRECOGNIZED_CHARACTER:
  206. *errmsg = "unrecognized character after (?";
  207. break;
  208. case 124:
  209. *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
  210. *errmsg = "unrecognized character after (?<";
  211. break;
  212. case 141:
  213. *errcode = G_REGEX_ERROR_UNRECOGNIZED_CHARACTER;
  214. *errmsg = "unrecognized character after (?P";
  215. break;
  216. case G_REGEX_ERROR_POSIX_NAMED_CLASS_OUTSIDE_CLASS:
  217. *errmsg = "POSIX named classes are supported only within a class";
  218. break;
  219. case G_REGEX_ERROR_UNMATCHED_PARENTHESIS:
  220. *errmsg = "missing terminating )";
  221. break;
  222. case 122:
  223. *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
  224. *errmsg = ") without opening (";
  225. break;
  226. case 129:
  227. *errcode = G_REGEX_ERROR_UNMATCHED_PARENTHESIS;
  228. /* translators: '(?R' and '(?[+-]digits' are both meant as (groups of)
  229. * sequences here, '(?-54' would be an example for the second group.
  230. */
  231. *errmsg = "(?R or (?[+-]digits must be followed by )";
  232. break;
  233. case G_REGEX_ERROR_INEXISTENT_SUBPATTERN_REFERENCE:
  234. *errmsg = "reference to non-existent subpattern";
  235. break;
  236. case G_REGEX_ERROR_UNTERMINATED_COMMENT:
  237. *errmsg = "missing ) after comment";
  238. break;
  239. case G_REGEX_ERROR_EXPRESSION_TOO_LARGE:
  240. *errmsg = "regular expression too large";
  241. break;
  242. case G_REGEX_ERROR_MEMORY_ERROR:
  243. *errmsg = "failed to get memory";
  244. break;
  245. case G_REGEX_ERROR_VARIABLE_LENGTH_LOOKBEHIND:
  246. *errmsg = "lookbehind assertion is not fixed length";
  247. break;
  248. case G_REGEX_ERROR_MALFORMED_CONDITION:
  249. *errmsg = "malformed number or name after (?(";
  250. break;
  251. case G_REGEX_ERROR_TOO_MANY_CONDITIONAL_BRANCHES:
  252. *errmsg = "conditional group contains more than two branches";
  253. break;
  254. case G_REGEX_ERROR_ASSERTION_EXPECTED:
  255. *errmsg = "assertion expected after (?(";
  256. break;
  257. case G_REGEX_ERROR_UNKNOWN_POSIX_CLASS_NAME:
  258. *errmsg = "unknown POSIX class name";
  259. break;
  260. case G_REGEX_ERROR_POSIX_COLLATING_ELEMENTS_NOT_SUPPORTED:
  261. *errmsg = "POSIX collating elements are not supported";
  262. break;
  263. case G_REGEX_ERROR_HEX_CODE_TOO_LARGE:
  264. *errmsg = "character value in \\x{...} sequence is too large";
  265. break;
  266. case G_REGEX_ERROR_INVALID_CONDITION:
  267. *errmsg = "invalid condition (?(0)";
  268. break;
  269. case G_REGEX_ERROR_SINGLE_BYTE_MATCH_IN_LOOKBEHIND:
  270. *errmsg = "\\C not allowed in lookbehind assertion";
  271. break;
  272. case G_REGEX_ERROR_INFINITE_LOOP:
  273. *errmsg = "recursive call could loop indefinitely";
  274. break;
  275. case G_REGEX_ERROR_MISSING_SUBPATTERN_NAME_TERMINATOR:
  276. *errmsg = "missing terminator in subpattern name";
  277. break;
  278. case G_REGEX_ERROR_DUPLICATE_SUBPATTERN_NAME:
  279. *errmsg = "two named subpatterns have the same name";
  280. break;
  281. case G_REGEX_ERROR_MALFORMED_PROPERTY:
  282. *errmsg = "malformed \\P or \\p sequence";
  283. break;
  284. case G_REGEX_ERROR_UNKNOWN_PROPERTY:
  285. *errmsg = "unknown property name after \\P or \\p";
  286. break;
  287. case G_REGEX_ERROR_SUBPATTERN_NAME_TOO_LONG:
  288. *errmsg = "subpattern name is too long (maximum 32 characters)";
  289. break;
  290. case G_REGEX_ERROR_TOO_MANY_SUBPATTERNS:
  291. *errmsg = "too many named subpatterns (maximum 10,000)";
  292. break;
  293. case G_REGEX_ERROR_INVALID_OCTAL_VALUE:
  294. *errmsg = "octal value is greater than \\377";
  295. break;
  296. case G_REGEX_ERROR_TOO_MANY_BRANCHES_IN_DEFINE:
  297. *errmsg = "DEFINE group contains more than one branch";
  298. break;
  299. case G_REGEX_ERROR_DEFINE_REPETION:
  300. *errmsg = "repeating a DEFINE group is not allowed";
  301. break;
  302. case G_REGEX_ERROR_INCONSISTENT_NEWLINE_OPTIONS:
  303. *errmsg = "inconsistent NEWLINE options";
  304. break;
  305. case G_REGEX_ERROR_MISSING_BACK_REFERENCE:
  306. *errmsg = "\\g is not followed by a braced name or an optionally "
  307. "braced non-zero number";
  308. break;
  309. case 11:
  310. *errcode = G_REGEX_ERROR_INTERNAL;
  311. *errmsg = "unexpected repeat";
  312. break;
  313. case 23:
  314. *errcode = G_REGEX_ERROR_INTERNAL;
  315. *errmsg = "code overflow";
  316. break;
  317. case 52:
  318. *errcode = G_REGEX_ERROR_INTERNAL;
  319. *errmsg = "overran compiling workspace";
  320. break;
  321. case 53:
  322. *errcode = G_REGEX_ERROR_INTERNAL;
  323. *errmsg = "previously-checked referenced subpattern not found";
  324. break;
  325. case 16:
  326. /* This should not happen as we never pass a NULL erroffset */
  327. g_warning ("erroffset passed as NULL");
  328. *errcode = G_REGEX_ERROR_COMPILE;
  329. break;
  330. case 17:
  331. /* This should not happen as we check options before passing them
  332. * to pcre_compile2() */
  333. g_warning ("unknown option bit(s) set");
  334. *errcode = G_REGEX_ERROR_COMPILE;
  335. break;
  336. case 32:
  337. case 44:
  338. case 45:
  339. /* These errors should not happen as we are using an UTF8-enabled PCRE
  340. * and we do not check if strings are valid */
  341. g_warning ("%s", *errmsg);
  342. *errcode = G_REGEX_ERROR_COMPILE;
  343. break;
  344. default:
  345. *errcode = G_REGEX_ERROR_COMPILE;
  346. }
  347. }
  348. /* GMatchInfo */
  349. static GMatchInfo *
  350. match_info_new (const GRegex *regex,
  351. const gchar *string,
  352. gint string_len,
  353. gint start_position,
  354. gint match_options,
  355. gboolean is_dfa)
  356. {
  357. GMatchInfo *match_info;
  358. if (string_len < 0)
  359. string_len = strlen (string);
  360. match_info = g_new0 (GMatchInfo, 1);
  361. match_info->regex = g_regex_ref ((GRegex *)regex);
  362. match_info->string = string;
  363. match_info->string_len = string_len;
  364. match_info->matches = PCRE_ERROR_NOMATCH;
  365. match_info->pos = start_position;
  366. match_info->match_opts = match_options;
  367. if (is_dfa)
  368. {
  369. /* These values should be enough for most cases, if they are not
  370. * enough g_regex_match_all_full() will expand them. */
  371. match_info->n_offsets = 24;
  372. match_info->n_workspace = 100;
  373. match_info->workspace = g_new (gint, match_info->n_workspace);
  374. }
  375. else
  376. {
  377. gint capture_count;
  378. pcre_fullinfo (regex->pcre_re, regex->extra,
  379. PCRE_INFO_CAPTURECOUNT, &capture_count);
  380. match_info->n_offsets = (capture_count + 1) * 3;
  381. }
  382. match_info->offsets = g_new0 (gint, match_info->n_offsets);
  383. /* Set an invalid position for the previous match. */
  384. match_info->offsets[0] = -1;
  385. match_info->offsets[1] = -1;
  386. return match_info;
  387. }
  388. /**
  389. * g_match_info_get_regex:
  390. * @match_info: a #GMatchInfo
  391. *
  392. * Returns #GRegex object used in @match_info. It belongs to Glib
  393. * and must not be freed. Use g_regex_ref() if you need to keep it
  394. * after you free @match_info object.
  395. *
  396. * Returns: #GRegex object used in @match_info
  397. *
  398. * Since: 2.14
  399. */
  400. GRegex *
  401. g_match_info_get_regex (const GMatchInfo *match_info)
  402. {
  403. g_return_val_if_fail (match_info != NULL, NULL);
  404. return match_info->regex;
  405. }
  406. /**
  407. * g_match_info_get_string:
  408. * @match_info: a #GMatchInfo
  409. *
  410. * Returns the string searched with @match_info. This is the
  411. * string passed to g_regex_match() or g_regex_replace() so
  412. * you may not free it before calling this function.
  413. *
  414. * Returns: the string searched with @match_info
  415. *
  416. * Since: 2.14
  417. */
  418. const gchar *
  419. g_match_info_get_string (const GMatchInfo *match_info)
  420. {
  421. g_return_val_if_fail (match_info != NULL, NULL);
  422. return match_info->string;
  423. }
  424. /**
  425. * g_match_info_free:
  426. * @match_info: a #GMatchInfo
  427. *
  428. * Frees all the memory associated with the #GMatchInfo structure.
  429. *
  430. * Since: 2.14
  431. */
  432. void
  433. g_match_info_free (GMatchInfo *match_info)
  434. {
  435. if (match_info)
  436. {
  437. g_regex_unref (match_info->regex);
  438. g_free (match_info->offsets);
  439. g_free (match_info->workspace);
  440. g_free (match_info);
  441. }
  442. }
  443. /**
  444. * g_match_info_next:
  445. * @match_info: a #GMatchInfo structure
  446. * @error: location to store the error occuring, or %NULL to ignore errors
  447. *
  448. * Scans for the next match using the same parameters of the previous
  449. * call to g_regex_match_full() or g_regex_match() that returned
  450. * @match_info.
  451. *
  452. * The match is done on the string passed to the match function, so you
  453. * cannot free it before calling this function.
  454. *
  455. * Returns: %TRUE is the string matched, %FALSE otherwise
  456. *
  457. * Since: 2.14
  458. */
  459. gboolean
  460. g_match_info_next (GMatchInfo *match_info,
  461. GError **error)
  462. {
  463. gint prev_match_start;
  464. gint prev_match_end;
  465. g_return_val_if_fail (match_info != NULL, FALSE);
  466. g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
  467. g_return_val_if_fail (match_info->pos >= 0, FALSE);
  468. prev_match_start = match_info->offsets[0];
  469. prev_match_end = match_info->offsets[1];
  470. match_info->matches = pcre_exec (match_info->regex->pcre_re,
  471. match_info->regex->extra,
  472. match_info->string,
  473. match_info->string_len,
  474. match_info->pos,
  475. match_info->regex->match_opts | match_info->match_opts,
  476. match_info->offsets,
  477. match_info->n_offsets);
  478. if (IS_PCRE_ERROR (match_info->matches))
  479. {
  480. g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
  481. "Error while matching regular expression %s: %s",
  482. match_info->regex->pattern, match_error (match_info->matches));
  483. return FALSE;
  484. }
  485. /* avoid infinite loops if the pattern is an empty string or something
  486. * equivalent */
  487. if (match_info->pos == match_info->offsets[1])
  488. {
  489. if (match_info->pos > match_info->string_len)
  490. {
  491. /* we have reached the end of the string */
  492. match_info->pos = -1;
  493. match_info->matches = PCRE_ERROR_NOMATCH;
  494. return FALSE;
  495. }
  496. match_info->pos = NEXT_CHAR (match_info->regex,
  497. &match_info->string[match_info->pos]) -
  498. match_info->string;
  499. }
  500. else
  501. {
  502. match_info->pos = match_info->offsets[1];
  503. }
  504. /* it's possibile to get two identical matches when we are matching
  505. * empty strings, for instance if the pattern is "(?=[A-Z0-9])" and
  506. * the string is "RegExTest" we have:
  507. * - search at position 0: match from 0 to 0
  508. * - search at position 1: match from 3 to 3
  509. * - search at position 3: match from 3 to 3 (duplicate)
  510. * - search at position 4: match from 5 to 5
  511. * - search at position 5: match from 5 to 5 (duplicate)
  512. * - search at position 6: no match -> stop
  513. * so we have to ignore the duplicates.
  514. * see bug #515944: http://bugzilla.gnome.org/show_bug.cgi?id=515944 */
  515. if (match_info->matches >= 0 &&
  516. prev_match_start == match_info->offsets[0] &&
  517. prev_match_end == match_info->offsets[1])
  518. {
  519. /* ignore this match and search the next one */
  520. return g_match_info_next (match_info, error);
  521. }
  522. return match_info->matches >= 0;
  523. }
  524. /**
  525. * g_match_info_matches:
  526. * @match_info: a #GMatchInfo structure
  527. *
  528. * Returns whether the previous match operation succeeded.
  529. *
  530. * Returns: %TRUE if the previous match operation succeeded,
  531. * %FALSE otherwise
  532. *
  533. * Since: 2.14
  534. */
  535. gboolean
  536. g_match_info_matches (const GMatchInfo *match_info)
  537. {
  538. g_return_val_if_fail (match_info != NULL, FALSE);
  539. return match_info->matches >= 0;
  540. }
  541. /**
  542. * g_match_info_get_match_count:
  543. * @match_info: a #GMatchInfo structure
  544. *
  545. * Retrieves the number of matched substrings (including substring 0,
  546. * that is the whole matched text), so 1 is returned if the pattern
  547. * has no substrings in it and 0 is returned if the match failed.
  548. *
  549. * If the last match was obtained using the DFA algorithm, that is
  550. * using g_regex_match_all() or g_regex_match_all_full(), the retrieved
  551. * count is not that of the number of capturing parentheses but that of
  552. * the number of matched substrings.
  553. *
  554. * Returns: Number of matched substrings, or -1 if an error occurred
  555. *
  556. * Since: 2.14
  557. */
  558. gint
  559. g_match_info_get_match_count (const GMatchInfo *match_info)
  560. {
  561. g_return_val_if_fail (match_info, -1);
  562. if (match_info->matches == PCRE_ERROR_NOMATCH)
  563. /* no match */
  564. return 0;
  565. else if (match_info->matches < PCRE_ERROR_NOMATCH)
  566. /* error */
  567. return -1;
  568. else
  569. /* match */
  570. return match_info->matches;
  571. }
  572. /**
  573. * g_match_info_is_partial_match:
  574. * @match_info: a #GMatchInfo structure
  575. *
  576. * Usually if the string passed to g_regex_match*() matches as far as
  577. * it goes, but is too short to match the entire pattern, %FALSE is
  578. * returned. There are circumstances where it might be helpful to
  579. * distinguish this case from other cases in which there is no match.
  580. *
  581. * Consider, for example, an application where a human is required to
  582. * type in data for a field with specific formatting requirements. An
  583. * example might be a date in the form ddmmmyy, defined by the pattern
  584. * "^\d?\d(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d\d$".
  585. * If the application sees the user’s keystrokes one by one, and can
  586. * check that what has been typed so far is potentially valid, it is
  587. * able to raise an error as soon as a mistake is made.
  588. *
  589. * GRegex supports the concept of partial matching by means of the
  590. * #G_REGEX_MATCH_PARTIAL flag. When this is set the return code for
  591. * g_regex_match() or g_regex_match_full() is, as usual, %TRUE
  592. * for a complete match, %FALSE otherwise. But, when these functions
  593. * return %FALSE, you can check if the match was partial calling
  594. * g_match_info_is_partial_match().
  595. *
  596. * When using partial matching you cannot use g_match_info_fetch*().
  597. *
  598. * Because of the way certain internal optimizations are implemented
  599. * the partial matching algorithm cannot be used with all patterns.
  600. * So repeated single characters such as "a{2,4}" and repeated single
  601. * meta-sequences such as "\d+" are not permitted if the maximum number
  602. * of occurrences is greater than one. Optional items such as "\d?"
  603. * (where the maximum is one) are permitted. Quantifiers with any values
  604. * are permitted after parentheses, so the invalid examples above can be
  605. * coded thus "(a){2,4}" and "(\d)+". If #G_REGEX_MATCH_PARTIAL is set
  606. * for a pattern that does not conform to the restrictions, matching
  607. * functions return an error.
  608. *
  609. * Returns: %TRUE if the match was partial, %FALSE otherwise
  610. *
  611. * Since: 2.14
  612. */
  613. gboolean
  614. g_match_info_is_partial_match (const GMatchInfo *match_info)
  615. {
  616. g_return_val_if_fail (match_info != NULL, FALSE);
  617. return match_info->matches == PCRE_ERROR_PARTIAL;
  618. }
  619. /**
  620. * g_match_info_expand_references:
  621. * @match_info: a #GMatchInfo or %NULL
  622. * @string_to_expand: the string to expand
  623. * @error: location to store the error occuring, or %NULL to ignore errors
  624. *
  625. * Returns a new string containing the text in @string_to_expand with
  626. * references and escape sequences expanded. References refer to the last
  627. * match done with @string against @regex and have the same syntax used by
  628. * g_regex_replace().
  629. *
  630. * The @string_to_expand must be UTF-8 encoded even if #G_REGEX_RAW was
  631. * passed to g_regex_new().
  632. *
  633. * The backreferences are extracted from the string passed to the match
  634. * function, so you cannot call this function after freeing the string.
  635. *
  636. * @match_info may be %NULL in which case @string_to_expand must not
  637. * contain references. For instance "foo\n" does not refer to an actual
  638. * pattern and '\n' merely will be replaced with \n character,
  639. * while to expand "\0" (whole match) one needs the result of a match.
  640. * Use g_regex_check_replacement() to find out whether @string_to_expand
  641. * contains references.
  642. *
  643. * Returns: the expanded string, or %NULL if an error occurred
  644. *
  645. * Since: 2.14
  646. */
  647. gchar *
  648. g_match_info_expand_references (const GMatchInfo *match_info,
  649. const gchar *string_to_expand,
  650. GError **error)
  651. {
  652. GString *result;
  653. GList *list;
  654. GError *tmp_error = NULL;
  655. g_return_val_if_fail (string_to_expand != NULL, NULL);
  656. g_return_val_if_fail (error == NULL || *error == NULL, NULL);
  657. list = split_replacement (string_to_expand, &tmp_error);
  658. if (tmp_error != NULL)
  659. {
  660. g_propagate_error (error, tmp_error);
  661. return NULL;
  662. }
  663. if (!match_info && interpolation_list_needs_match (list))
  664. {
  665. g_critical ("String '%s' contains references to the match, can't "
  666. "expand references without GMatchInfo object",
  667. string_to_expand);
  668. return NULL;
  669. }
  670. result = g_string_sized_new (strlen (string_to_expand));
  671. interpolate_replacement (match_info, result, list);
  672. g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
  673. g_list_free (list);
  674. return g_string_free (result, FALSE);
  675. }
  676. /**
  677. * g_match_info_fetch:
  678. * @match_info: #GMatchInfo structure
  679. * @match_num: number of the sub expression
  680. *
  681. * Retrieves the text matching the @match_num<!-- -->'th capturing
  682. * parentheses. 0 is the full text of the match, 1 is the first paren
  683. * set, 2 the second, and so on.
  684. *
  685. * If @match_num is a valid sub pattern but it didn't match anything
  686. * (e.g. sub pattern 1, matching "b" against "(a)?b") then an empty
  687. * string is returned.
  688. *
  689. * If the match was obtained using the DFA algorithm, that is using
  690. * g_regex_match_all() or g_regex_match_all_full(), the retrieved
  691. * string is not that of a set of parentheses but that of a matched
  692. * substring. Substrings are matched in reverse order of length, so
  693. * 0 is the longest match.
  694. *
  695. * The string is fetched from the string passed to the match function,
  696. * so you cannot call this function after freeing the string.
  697. *
  698. * Returns: The matched substring, or %NULL if an error occurred.
  699. * You have to free the string yourself
  700. *
  701. * Since: 2.14
  702. */
  703. gchar *
  704. g_match_info_fetch (const GMatchInfo *match_info,
  705. gint match_num)
  706. {
  707. /* we cannot use pcre_get_substring() because it allocates the
  708. * string using pcre_malloc(). */
  709. gchar *match = NULL;
  710. gint start, end;
  711. g_return_val_if_fail (match_info != NULL, NULL);
  712. g_return_val_if_fail (match_num >= 0, NULL);
  713. /* match_num does not exist or it didn't matched, i.e. matching "b"
  714. * against "(a)?b" then group 0 is empty. */
  715. if (!g_match_info_fetch_pos (match_info, match_num, &start, &end))
  716. match = NULL;
  717. else if (start == -1)
  718. match = g_strdup ("");
  719. else
  720. match = g_strndup (&match_info->string[start], end - start);
  721. return match;
  722. }
  723. /**
  724. * g_match_info_fetch_pos:
  725. * @match_info: #GMatchInfo structure
  726. * @match_num: number of the sub expression
  727. * @start_pos: pointer to location where to store the start position
  728. * @end_pos: pointer to location where to store the end position
  729. *
  730. * Retrieves the position in bytes of the @match_num<!-- -->'th capturing
  731. * parentheses. 0 is the full text of the match, 1 is the first
  732. * paren set, 2 the second, and so on.
  733. *
  734. * If @match_num is a valid sub pattern but it didn't match anything
  735. * (e.g. sub pattern 1, matching "b" against "(a)?b") then @start_pos
  736. * and @end_pos are set to -1 and %TRUE is returned.
  737. *
  738. * If the match was obtained using the DFA algorithm, that is using
  739. * g_regex_match_all() or g_regex_match_all_full(), the retrieved
  740. * position is not that of a set of parentheses but that of a matched
  741. * substring. Substrings are matched in reverse order of length, so
  742. * 0 is the longest match.
  743. *
  744. * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
  745. * the position cannot be fetched, @start_pos and @end_pos are left
  746. * unchanged
  747. *
  748. * Since: 2.14
  749. */
  750. gboolean
  751. g_match_info_fetch_pos (const GMatchInfo *match_info,
  752. gint match_num,
  753. gint *start_pos,
  754. gint *end_pos)
  755. {
  756. g_return_val_if_fail (match_info != NULL, FALSE);
  757. g_return_val_if_fail (match_num >= 0, FALSE);
  758. /* make sure the sub expression number they're requesting is less than
  759. * the total number of sub expressions that were matched. */
  760. if (match_num >= match_info->matches)
  761. return FALSE;
  762. if (start_pos != NULL)
  763. *start_pos = match_info->offsets[2 * match_num];
  764. if (end_pos != NULL)
  765. *end_pos = match_info->offsets[2 * match_num + 1];
  766. return TRUE;
  767. }
  768. static gint
  769. int_pcre_get_stringtable_entries(const pcre *code, const gchar *stringname,
  770. gchar **firstptr, gchar **lastptr)
  771. {
  772. gint rc;
  773. gint entrysize;
  774. gint top, bot;
  775. guchar *nametable, *lastentry;
  776. if ((rc = pcre_fullinfo (code, NULL, PCRE_INFO_NAMECOUNT, &top)) != 0)
  777. return rc;
  778. if (top <= 0)
  779. return PCRE_ERROR_NOSUBSTRING;
  780. if ((rc = pcre_fullinfo (code, NULL, PCRE_INFO_NAMEENTRYSIZE, &entrysize))
  781. != 0)
  782. return rc;
  783. if ((rc = pcre_fullinfo (code, NULL, PCRE_INFO_NAMETABLE, &nametable)) != 0)
  784. return rc;
  785. lastentry = nametable + entrysize * (top - 1);
  786. bot = 0;
  787. while (top > bot)
  788. {
  789. int mid = (top + bot) / 2;
  790. char *entry = nametable + entrysize * mid;
  791. int c = strcmp (stringname, (char *) (entry + 2));
  792. if (c == 0) {
  793. char *first = entry;
  794. char *last = entry;
  795. while (first > nametable) {
  796. if (strcmp (stringname, (char *) (first - entrysize + 2)) != 0)break
  797. ; first -= entrysize;
  798. }
  799. while (last < lastentry) {
  800. if (strcmp (stringname, (char *) (last + entrysize + 2)) != 0)break
  801. ; last += entrysize;
  802. }
  803. *firstptr = (char *) first;
  804. *lastptr = (char *) last;
  805. return entrysize;
  806. }
  807. if (c > 0)
  808. bot = mid + 1;
  809. else
  810. top = mid;
  811. }
  812. return PCRE_ERROR_NOSUBSTRING;
  813. }
  814. /*
  815. * Returns number of first matched subpattern with name @name.
  816. * There may be more than one in case when DUPNAMES is used,
  817. * and not all subpatterns with that name match;
  818. * pcre_get_stringnumber() does not work in that case.
  819. */
  820. static gint
  821. get_matched_substring_number (const GMatchInfo *match_info,
  822. const gchar *name)
  823. {
  824. gint entrysize;
  825. gchar *first, *last;
  826. guchar *entry;
  827. if (!(match_info->regex->compile_opts & G_REGEX_DUPNAMES))
  828. return pcre_get_stringnumber (match_info->regex->pcre_re, name);
  829. /* This code is copied from pcre_get.c: get_first_set() */
  830. entrysize = int_pcre_get_stringtable_entries (match_info->regex->pcre_re,
  831. name,
  832. &first,
  833. &last);
  834. if (entrysize <= 0)
  835. return entrysize;
  836. for (entry = (guchar*) first; entry <= (guchar*) last; entry += entrysize)
  837. {
  838. gint n = (entry[0] << 8) + entry[1];
  839. if (match_info->offsets[n*2] >= 0)
  840. return n;
  841. }
  842. return (first[0] << 8) + first[1];
  843. }
  844. /**
  845. * g_match_info_fetch_named:
  846. * @match_info: #GMatchInfo structure
  847. * @name: name of the subexpression
  848. *
  849. * Retrieves the text matching the capturing parentheses named @name.
  850. *
  851. * If @name is a valid sub pattern name but it didn't match anything
  852. * (e.g. sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b")
  853. * then an empty string is returned.
  854. *
  855. * The string is fetched from the string passed to the match function,
  856. * so you cannot call this function after freeing the string.
  857. *
  858. * Returns: The matched substring, or %NULL if an error occurred.
  859. * You have to free the string yourself
  860. *
  861. * Since: 2.14
  862. */
  863. gchar *
  864. g_match_info_fetch_named (const GMatchInfo *match_info,
  865. const gchar *name)
  866. {
  867. /* we cannot use pcre_get_named_substring() because it allocates the
  868. * string using pcre_malloc(). */
  869. gint num;
  870. g_return_val_if_fail (match_info != NULL, NULL);
  871. g_return_val_if_fail (name != NULL, NULL);
  872. num = get_matched_substring_number (match_info, name);
  873. if (num < 0)
  874. return NULL;
  875. else
  876. return g_match_info_fetch (match_info, num);
  877. }
  878. /**
  879. * g_match_info_fetch_named_pos:
  880. * @match_info: #GMatchInfo structure
  881. * @name: name of the subexpression
  882. * @start_pos: pointer to location where to store the start position
  883. * @end_pos: pointer to location where to store the end position
  884. *
  885. * Retrieves the position in bytes of the capturing parentheses named @name.
  886. *
  887. * If @name is a valid sub pattern name but it didn't match anything
  888. * (e.g. sub pattern "X", matching "b" against "(?P&lt;X&gt;a)?b")
  889. * then @start_pos and @end_pos are set to -1 and %TRUE is returned.
  890. *
  891. * Returns: %TRUE if the position was fetched, %FALSE otherwise. If
  892. * the position cannot be fetched, @start_pos and @end_pos are left
  893. * unchanged
  894. *
  895. * Since: 2.14
  896. */
  897. gboolean
  898. g_match_info_fetch_named_pos (const GMatchInfo *match_info,
  899. const gchar *name,
  900. gint *start_pos,
  901. gint *end_pos)
  902. {
  903. gint num;
  904. g_return_val_if_fail (match_info != NULL, FALSE);
  905. g_return_val_if_fail (name != NULL, FALSE);
  906. num = get_matched_substring_number (match_info, name);
  907. if (num < 0)
  908. return FALSE;
  909. return g_match_info_fetch_pos (match_info, num, start_pos, end_pos);
  910. }
  911. /**
  912. * g_match_info_fetch_all:
  913. * @match_info: a #GMatchInfo structure
  914. *
  915. * Bundles up pointers to each of the matching substrings from a match
  916. * and stores them in an array of gchar pointers. The first element in
  917. * the returned array is the match number 0, i.e. the entire matched
  918. * text.
  919. *
  920. * If a sub pattern didn't match anything (e.g. sub pattern 1, matching
  921. * "b" against "(a)?b") then an empty string is inserted.
  922. *
  923. * If the last match was obtained using the DFA algorithm, that is using
  924. * g_regex_match_all() or g_regex_match_all_full(), the retrieved
  925. * strings are not that matched by sets of parentheses but that of the
  926. * matched substring. Substrings are matched in reverse order of length,
  927. * so the first one is the longest match.
  928. *
  929. * The strings are fetched from the string passed to the match function,
  930. * so you cannot call this function after freeing the string.
  931. *
  932. * Returns: a %NULL-terminated array of gchar * pointers. It must be
  933. * freed using g_strfreev(). If the previous match failed %NULL is
  934. * returned
  935. *
  936. * Since: 2.14
  937. */
  938. gchar **
  939. g_match_info_fetch_all (const GMatchInfo *match_info)
  940. {
  941. /* we cannot use pcre_get_substring_list() because the returned value
  942. * isn't suitable for g_strfreev(). */
  943. gchar **result;
  944. gint i;
  945. g_return_val_if_fail (match_info != NULL, NULL);
  946. if (match_info->matches < 0)
  947. return NULL;
  948. result = g_new (gchar *, match_info->matches + 1);
  949. for (i = 0; i < match_info->matches; i++)
  950. result[i] = g_match_info_fetch (match_info, i);
  951. result[i] = NULL;
  952. return result;
  953. }
  954. /* GRegex */
  955. GQuark
  956. g_regex_error_quark (void)
  957. {
  958. static GQuark error_quark = 0;
  959. if (error_quark == 0)
  960. error_quark = g_quark_from_static_string ("g-regex-error-quark");
  961. return error_quark;
  962. }
  963. /**
  964. * g_regex_ref:
  965. * @regex: a #GRegex
  966. *
  967. * Increases reference count of @regex by 1.
  968. *
  969. * Returns: @regex
  970. *
  971. * Since: 2.14
  972. */
  973. GRegex *
  974. g_regex_ref (GRegex *regex)
  975. {
  976. g_return_val_if_fail (regex != NULL, NULL);
  977. g_atomic_int_inc (&regex->ref_count);
  978. return regex;
  979. }
  980. /**
  981. * g_regex_unref:
  982. * @regex: a #GRegex
  983. *
  984. * Decreases reference count of @regex by 1. When reference count drops
  985. * to zero, it frees all the memory associated with the regex structure.
  986. *
  987. * Since: 2.14
  988. */
  989. void
  990. g_regex_unref (GRegex *regex)
  991. {
  992. g_return_if_fail (regex != NULL);
  993. if (g_atomic_int_exchange_and_add (&regex->ref_count, -1) - 1 == 0)
  994. {
  995. g_free (regex->pattern);
  996. if (regex->pcre_re != NULL)
  997. pcre_free (regex->pcre_re);
  998. if (regex->extra != NULL)
  999. pcre_free (regex->extra);
  1000. g_free (regex);
  1001. }
  1002. }
  1003. /**
  1004. * g_regex_new:
  1005. * @pattern: the regular expression
  1006. * @compile_options: compile options for the regular expression, or 0
  1007. * @match_options: match options for the regular expression, or 0
  1008. * @error: return location for a #GError
  1009. *
  1010. * Compiles the regular expression to an internal form, and does
  1011. * the initial setup of the #GRegex structure.
  1012. *
  1013. * Returns: a #GRegex structure. Call g_regex_unref() when you
  1014. * are done with it
  1015. *
  1016. * Since: 2.14
  1017. */
  1018. GRegex *
  1019. g_regex_new (const gchar *pattern,
  1020. GRegexCompileFlags compile_options,
  1021. GRegexMatchFlags match_options,
  1022. GError **error)
  1023. {
  1024. GRegex *regex;
  1025. pcre *re;
  1026. const gchar *errmsg;
  1027. gint erroffset;
  1028. gint errcode;
  1029. gboolean optimize = FALSE;
  1030. static gboolean initialized = FALSE;
  1031. unsigned long int pcre_compile_options;
  1032. g_return_val_if_fail (pattern != NULL, NULL);
  1033. g_return_val_if_fail (error == NULL || *error == NULL, NULL);
  1034. g_return_val_if_fail ((compile_options & ~G_REGEX_COMPILE_MASK) == 0, NULL);
  1035. g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
  1036. if (!initialized)
  1037. {
  1038. gint support;
  1039. const gchar *msg;
  1040. pcre_config (PCRE_CONFIG_UTF8, &support);
  1041. if (!support)
  1042. {
  1043. msg = "PCRE library is compiled without UTF8 support";
  1044. g_critical ("%s", msg);
  1045. g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, msg);
  1046. return NULL;
  1047. }
  1048. pcre_config (PCRE_CONFIG_UNICODE_PROPERTIES, &support);
  1049. if (!support)
  1050. {
  1051. msg = "PCRE library is compiled without UTF8 properties support";
  1052. g_critical ("%s", msg);
  1053. g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_COMPILE, msg);
  1054. return NULL;
  1055. }
  1056. initialized = TRUE;
  1057. }
  1058. /* G_REGEX_OPTIMIZE has the same numeric value of PCRE_NO_UTF8_CHECK,
  1059. * as we do not need to wrap PCRE_NO_UTF8_CHECK. */
  1060. if (compile_options & G_REGEX_OPTIMIZE)
  1061. optimize = TRUE;
  1062. /* In GRegex the string are, by default, UTF-8 encoded. PCRE
  1063. * instead uses UTF-8 only if required with PCRE_UTF8. */
  1064. if (compile_options & G_REGEX_RAW)
  1065. {
  1066. /* disable utf-8 */
  1067. compile_options &= ~G_REGEX_RAW;
  1068. }
  1069. else
  1070. {
  1071. /* enable utf-8 */
  1072. compile_options |= PCRE_UTF8 | PCRE_NO_UTF8_CHECK;
  1073. match_options |= PCRE_NO_UTF8_CHECK;
  1074. }
  1075. /* PCRE_NEWLINE_ANY is the default for the internal PCRE but
  1076. * not for the system one. */
  1077. /* compile the pattern */
  1078. re = pcre_compile2 (pattern, compile_options, &errcode,
  1079. &errmsg, &erroffset, NULL);
  1080. /* if the compilation failed, set the error member and return
  1081. * immediately */
  1082. if (re == NULL)
  1083. {
  1084. GError *tmp_error;
  1085. /* Translate the PCRE error code to GRegexError and use a translated
  1086. * error message if possible */
  1087. translate_compile_error (&errcode, &errmsg);
  1088. /* PCRE uses byte offsets but we want to show character offsets */
  1089. erroffset = g_utf8_pointer_to_offset (pattern, &pattern[erroffset]);
  1090. tmp_error = g_error_new (G_REGEX_ERROR, errcode,
  1091. "Error while compiling regular "
  1092. "expression %s at char %d: %s",
  1093. pattern, erroffset, errmsg);
  1094. g_propagate_error (error, tmp_error);
  1095. return NULL;
  1096. }
  1097. /* For options set at the beginning of the pattern, pcre puts them into
  1098. * compile options, e.g. "(?i)foo" will make the pcre structure store
  1099. * PCRE_CASELESS even though it wasn't explicitly given for compilation. */
  1100. pcre_fullinfo (re, NULL, PCRE_INFO_OPTIONS, &pcre_compile_options);
  1101. compile_options = pcre_compile_options;
  1102. regex = g_new0 (GRegex, 1);
  1103. regex->ref_count = 1;
  1104. regex->pattern = g_strdup (pattern);
  1105. regex->pcre_re = re;
  1106. regex->compile_opts = compile_options;
  1107. regex->match_opts = match_options;
  1108. if (optimize)
  1109. {
  1110. regex->extra = pcre_study (regex->pcre_re, 0, &errmsg);
  1111. if (errmsg != NULL)
  1112. {
  1113. GError *tmp_error = g_error_new (G_REGEX_ERROR,
  1114. G_REGEX_ERROR_OPTIMIZE,
  1115. "Error while optimizing "
  1116. "regular expression %s: %s",
  1117. regex->pattern,
  1118. errmsg);
  1119. g_propagate_error (error, tmp_error);
  1120. g_regex_unref (regex);
  1121. return NULL;
  1122. }
  1123. }
  1124. return regex;
  1125. }
  1126. /**
  1127. * g_regex_get_pattern:
  1128. * @regex: a #GRegex structure
  1129. *
  1130. * Gets the pattern string associated with @regex, i.e. a copy of
  1131. * the string passed to g_regex_new().
  1132. *
  1133. * Returns: the pattern of @regex
  1134. *
  1135. * Since: 2.14
  1136. */
  1137. const gchar *
  1138. g_regex_get_pattern (const GRegex *regex)
  1139. {
  1140. g_return_val_if_fail (regex != NULL, NULL);
  1141. return regex->pattern;
  1142. }
  1143. /**
  1144. * g_regex_get_max_backref:
  1145. * @regex: a #GRegex
  1146. *
  1147. * Returns the number of the highest back reference
  1148. * in the pattern, or 0 if the pattern does not contain
  1149. * back references.
  1150. *
  1151. * Returns: the number of the highest back reference
  1152. *
  1153. * Since: 2.14
  1154. */
  1155. gint
  1156. g_regex_get_max_backref (const GRegex *regex)
  1157. {
  1158. gint value;
  1159. pcre_fullinfo (regex->pcre_re, regex->extra,
  1160. PCRE_INFO_BACKREFMAX, &value);
  1161. return value;
  1162. }
  1163. /**
  1164. * g_regex_get_capture_count:
  1165. * @regex: a #GRegex
  1166. *
  1167. * Returns the number of capturing subpatterns in the pattern.
  1168. *
  1169. * Returns: the number of capturing subpatterns
  1170. *
  1171. * Since: 2.14
  1172. */
  1173. gint
  1174. g_regex_get_capture_count (const GRegex *regex)
  1175. {
  1176. gint value;
  1177. pcre_fullinfo (regex->pcre_re, regex->extra,
  1178. PCRE_INFO_CAPTURECOUNT, &value);
  1179. return value;
  1180. }
  1181. /**
  1182. * g_regex_match_simple:
  1183. * @pattern: the regular expression
  1184. * @string: the string to scan for matches
  1185. * @compile_options: compile options for the regular expression, or 0
  1186. * @match_options: match options, or 0
  1187. *
  1188. * Scans for a match in @string for @pattern.
  1189. *
  1190. * This function is equivalent to g_regex_match() but it does not
  1191. * require to compile the pattern with g_regex_new(), avoiding some
  1192. * lines of code when you need just to do a match without extracting
  1193. * substrings, capture counts, and so on.
  1194. *
  1195. * If this function is to be called on the same @pattern more than
  1196. * once, it's more efficient to compile the pattern once with
  1197. * g_regex_new() and then use g_regex_match().
  1198. *
  1199. * Returns: %TRUE if the string matched, %FALSE otherwise
  1200. *
  1201. * Since: 2.14
  1202. */
  1203. gboolean
  1204. g_regex_match_simple (const gchar *pattern,
  1205. const gchar *string,
  1206. GRegexCompileFlags compile_options,
  1207. GRegexMatchFlags match_options)
  1208. {
  1209. GRegex *regex;
  1210. gboolean result;
  1211. regex = g_regex_new (pattern, compile_options, 0, NULL);
  1212. if (!regex)
  1213. return FALSE;
  1214. result = g_regex_match_full (regex, string, -1, 0, match_options, NULL, NULL);
  1215. g_regex_unref (regex);
  1216. return result;
  1217. }
  1218. /**
  1219. * g_regex_match:
  1220. * @regex: a #GRegex structure from g_regex_new()
  1221. * @string: the string to scan for matches
  1222. * @match_options: match options
  1223. * @match_info: pointer to location where to store the #GMatchInfo,
  1224. * or %NULL if you do not need it
  1225. *
  1226. * Scans for a match in string for the pattern in @regex.
  1227. * The @match_options are combined with the match options specified
  1228. * when the @regex structure was created, letting you have more
  1229. * flexibility in reusing #GRegex structures.
  1230. *
  1231. * A #GMatchInfo structure, used to get information on the match,
  1232. * is stored in @match_info if not %NULL. Note that if @match_info
  1233. * is not %NULL then it is created even if the function returns %FALSE,
  1234. * i.e. you must free it regardless if regular expression actually matched.
  1235. *
  1236. * To retrieve all the non-overlapping matches of the pattern in
  1237. * string you can use g_match_info_next().
  1238. *
  1239. * |[
  1240. * static void
  1241. * print_uppercase_words (const gchar *string)
  1242. * {
  1243. * /&ast; Print all uppercase-only words. &ast;/
  1244. * GRegex *regex;
  1245. * GMatchInfo *match_info;
  1246. * &nbsp;
  1247. * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
  1248. * g_regex_match (regex, string, 0, &amp;match_info);
  1249. * while (g_match_info_matches (match_info))
  1250. * {
  1251. * gchar *word = g_match_info_fetch (match_info, 0);
  1252. * g_print ("Found: %s\n", word);
  1253. * g_free (word);
  1254. * g_match_info_next (match_info, NULL);
  1255. * }
  1256. * g_match_info_free (match_info);
  1257. * g_regex_unref (regex);
  1258. * }
  1259. * ]|
  1260. *
  1261. * @string is not copied and is used in #GMatchInfo internally. If
  1262. * you use any #GMatchInfo method (except g_match_info_free()) after
  1263. * freeing or modifying @string then the behaviour is undefined.
  1264. *
  1265. * Returns: %TRUE is the string matched, %FALSE otherwise
  1266. *
  1267. * Since: 2.14
  1268. */
  1269. gboolean
  1270. g_regex_match (const GRegex *regex,
  1271. const gchar *string,
  1272. GRegexMatchFlags match_options,
  1273. GMatchInfo **match_info)
  1274. {
  1275. return g_regex_match_full (regex, string, -1, 0, match_options,
  1276. match_info, NULL);
  1277. }
  1278. /**
  1279. * g_regex_match_full:
  1280. * @regex: a #GRegex structure from g_regex_new()
  1281. * @string: the string to scan for matches
  1282. * @string_len: the length of @string, or -1 if @string is nul-terminated
  1283. * @start_position: starting index of the string to match
  1284. * @match_options: match options
  1285. * @match_info: pointer to location where to store the #GMatchInfo,
  1286. * or %NULL if you do not need it
  1287. * @error: location to store the error occuring, or %NULL to ignore errors
  1288. *
  1289. * Scans for a match in string for the pattern in @regex.
  1290. * The @match_options are combined with the match options specified
  1291. * when the @regex structure was created, letting you have more
  1292. * flexibility in reusing #GRegex structures.
  1293. *
  1294. * Setting @start_position differs from just passing over a shortened
  1295. * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
  1296. * that begins with any kind of lookbehind assertion, such as "\b".
  1297. *
  1298. * A #GMatchInfo structure, used to get information on the match, is
  1299. * stored in @match_info if not %NULL. Note that if @match_info is
  1300. * not %NULL then it is created even if the function returns %FALSE,
  1301. * i.e. you must free it regardless if regular expression actually
  1302. * matched.
  1303. *
  1304. * @string is not copied and is used in #GMatchInfo internally. If
  1305. * you use any #GMatchInfo method (except g_match_info_free()) after
  1306. * freeing or modifying @string then the behaviour is undefined.
  1307. *
  1308. * To retrieve all the non-overlapping matches of the pattern in
  1309. * string you can use g_match_info_next().
  1310. *
  1311. * |[
  1312. * static void
  1313. * print_uppercase_words (const gchar *string)
  1314. * {
  1315. * /&ast; Print all uppercase-only words. &ast;/
  1316. * GRegex *regex;
  1317. * GMatchInfo *match_info;
  1318. * GError *error = NULL;
  1319. * &nbsp;
  1320. * regex = g_regex_new ("[A-Z]+", 0, 0, NULL);
  1321. * g_regex_match_full (regex, string, -1, 0, 0, &amp;match_info, &amp;error);
  1322. * while (g_match_info_matches (match_info))
  1323. * {
  1324. * gchar *word = g_match_info_fetch (match_info, 0);
  1325. * g_print ("Found: %s\n", word);
  1326. * g_free (word);
  1327. * g_match_info_next (match_info, &amp;error);
  1328. * }
  1329. * g_match_info_free (match_info);
  1330. * g_regex_unref (regex);
  1331. * if (error != NULL)
  1332. * {
  1333. * g_printerr ("Error while matching: %s\n", error->message);
  1334. * g_error_free (error);
  1335. * }
  1336. * }
  1337. * ]|
  1338. *
  1339. * Returns: %TRUE is the string matched, %FALSE otherwise
  1340. *
  1341. * Since: 2.14
  1342. */
  1343. gboolean
  1344. g_regex_match_full (const GRegex *regex,
  1345. const gchar *string,
  1346. gssize string_len,
  1347. gint start_position,
  1348. GRegexMatchFlags match_options,
  1349. GMatchInfo **match_info,
  1350. GError **error)
  1351. {
  1352. GMatchInfo *info;
  1353. gboolean match_ok;
  1354. g_return_val_if_fail (regex != NULL, FALSE);
  1355. g_return_val_if_fail (string != NULL, FALSE);
  1356. g_return_val_if_fail (start_position >= 0, FALSE);
  1357. g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
  1358. g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
  1359. info = match_info_new (regex, string, string_len, start_position,
  1360. match_options, FALSE);
  1361. match_ok = g_match_info_next (info, error);
  1362. if (match_info != NULL)
  1363. *match_info = info;
  1364. else
  1365. g_match_info_free (info);
  1366. return match_ok;
  1367. }
  1368. /**
  1369. * g_regex_match_all:
  1370. * @regex: a #GRegex structure from g_regex_new()
  1371. * @string: the string to scan for matches
  1372. * @match_options: match options
  1373. * @match_info: pointer to location where to store the #GMatchInfo,
  1374. * or %NULL if you do not need it
  1375. *
  1376. * Using the standard algorithm for regular expression matching only
  1377. * the longest match in the string is retrieved. This function uses
  1378. * a different algorithm so it can retrieve all the possible matches.
  1379. * For more documentation see g_regex_match_all_full().
  1380. *
  1381. * A #GMatchInfo structure, used to get information on the match, is
  1382. * stored in @match_info if not %NULL. Note that if @match_info is
  1383. * not %NULL then it is created even if the function returns %FALSE,
  1384. * i.e. you must free it regardless if regular expression actually
  1385. * matched.
  1386. *
  1387. * @string is not copied and is used in #GMatchInfo internally. If
  1388. * you use any #GMatchInfo method (except g_match_info_free()) after
  1389. * freeing or modifying @string then the behaviour is undefined.
  1390. *
  1391. * Returns: %TRUE is the string matched, %FALSE otherwise
  1392. *
  1393. * Since: 2.14
  1394. */
  1395. gboolean
  1396. g_regex_match_all (const GRegex *regex,
  1397. const gchar *string,
  1398. GRegexMatchFlags match_options,
  1399. GMatchInfo **match_info)
  1400. {
  1401. return g_regex_match_all_full (regex, string, -1, 0, match_options,
  1402. match_info, NULL);
  1403. }
  1404. /**
  1405. * g_regex_match_all_full:
  1406. * @regex: a #GRegex structure from g_regex_new()
  1407. * @string: the string to scan for matches
  1408. * @string_len: the length of @string, or -1 if @string is nul-terminated
  1409. * @start_position: starting index of the string to match
  1410. * @match_options: match options
  1411. * @match_info: pointer to location where to store the #GMatchInfo,
  1412. * or %NULL if you do not need it
  1413. * @error: location to store the error occuring, or %NULL to ignore errors
  1414. *
  1415. * Using the standard algorithm for regular expression matching only
  1416. * the longest match in the string is retrieved, it is not possibile
  1417. * to obtain all the available matches. For instance matching
  1418. * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;"
  1419. * you get "&lt;a&gt; &lt;b&gt; &lt;c&gt;".
  1420. *
  1421. * This function uses a different algorithm (called DFA, i.e. deterministic
  1422. * finite automaton), so it can retrieve all the possible matches, all
  1423. * starting at the same point in the string. For instance matching
  1424. * "&lt;a&gt; &lt;b&gt; &lt;c&gt;" against the pattern "&lt;.*&gt;"
  1425. * you would obtain three matches: "&lt;a&gt; &lt;b&gt; &lt;c&gt;",
  1426. * "&lt;a&gt; &lt;b&gt;" and "&lt;a&gt;".
  1427. *
  1428. * The number of matched strings is retrieved using
  1429. * g_match_info_get_match_count(). To obtain the matched strings and
  1430. * their position you can use, respectively, g_match_info_fetch() and
  1431. * g_match_info_fetch_pos(). Note that the strings are returned in
  1432. * reverse order of length; that is, the longest matching string is
  1433. * given first.
  1434. *
  1435. * Note that the DFA algorithm is slower than the standard one and it
  1436. * is not able to capture substrings, so backreferences do not work.
  1437. *
  1438. * Setting @start_position differs from just passing over a shortened
  1439. * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
  1440. * that begins with any kind of lookbehind assertion, such as "\b".
  1441. *
  1442. * A #GMatchInfo structure, used to get information on the match, is
  1443. * stored in @match_info if not %NULL. Note that if @match_info is
  1444. * not %NULL then it is created even if the function returns %FALSE,
  1445. * i.e. you must free it regardless if regular expression actually
  1446. * matched.
  1447. *
  1448. * @string is not copied and is used in #GMatchInfo internally. If
  1449. * you use any #GMatchInfo method (except g_match_info_free()) after
  1450. * freeing or modifying @string then the behaviour is undefined.
  1451. *
  1452. * Returns: %TRUE is the string matched, %FALSE otherwise
  1453. *
  1454. * Since: 2.14
  1455. */
  1456. gboolean
  1457. g_regex_match_all_full (const GRegex *regex,
  1458. const gchar *string,
  1459. gssize string_len,
  1460. gint start_position,
  1461. GRegexMatchFlags match_options,
  1462. GMatchInfo **match_info,
  1463. GError **error)
  1464. {
  1465. GMatchInfo *info;
  1466. gboolean done;
  1467. g_return_val_if_fail (regex != NULL, FALSE);
  1468. g_return_val_if_fail (string != NULL, FALSE);
  1469. g_return_val_if_fail (start_position >= 0, FALSE);
  1470. g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
  1471. g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, FALSE);
  1472. info = match_info_new (regex, string, string_len, start_position,
  1473. match_options, TRUE);
  1474. done = FALSE;
  1475. while (!done)
  1476. {
  1477. done = TRUE;
  1478. info->matches = pcre_dfa_exec (regex->pcre_re, regex->extra,
  1479. info->string, info->string_len,
  1480. info->pos,
  1481. regex->match_opts | match_options,
  1482. info->offsets, info->n_offsets,
  1483. info->workspace, info->n_workspace);
  1484. if (info->matches == PCRE_ERROR_DFA_WSSIZE)
  1485. {
  1486. /* info->workspace is too small. */
  1487. info->n_workspace *= 2;
  1488. info->workspace = g_realloc (info->workspace,
  1489. info->n_workspace * sizeof (gint));
  1490. done = FALSE;
  1491. }
  1492. else if (info->matches == 0)
  1493. {
  1494. /* info->offsets is too small. */
  1495. info->n_offsets *= 2;
  1496. info->offsets = g_realloc (info->offsets,
  1497. info->n_offsets * sizeof (gint));
  1498. done = FALSE;
  1499. }
  1500. else if (IS_PCRE_ERROR (info->matches))
  1501. {
  1502. g_set_error (error, G_REGEX_ERROR, G_REGEX_ERROR_MATCH,
  1503. "Error while matching regular expression %s: %s",
  1504. regex->pattern, match_error (info->matches));
  1505. }
  1506. }
  1507. /* set info->pos to -1 so that a call to g_match_info_next() fails. */
  1508. info->pos = -1;
  1509. if (match_info != NULL)
  1510. *match_info = info;
  1511. else
  1512. g_match_info_free (info);
  1513. return info->matches >= 0;
  1514. }
  1515. /**
  1516. * g_regex_get_string_number:
  1517. * @regex: #GRegex structure
  1518. * @name: name of the subexpression
  1519. *
  1520. * Retrieves the number of the subexpression named @name.
  1521. *
  1522. * Returns: The number of the subexpression or -1 if @name
  1523. * does not exists
  1524. *
  1525. * Since: 2.14
  1526. */
  1527. gint
  1528. g_regex_get_string_number (const GRegex *regex,
  1529. const gchar *name)
  1530. {
  1531. gint num;
  1532. g_return_val_if_fail (regex != NULL, -1);
  1533. g_return_val_if_fail (name != NULL, -1);
  1534. num = pcre_get_stringnumber (regex->pcre_re, name);
  1535. if (num == PCRE_ERROR_NOSUBSTRING)
  1536. num = -1;
  1537. return num;
  1538. }
  1539. /**
  1540. * g_regex_split_simple:
  1541. * @pattern: the regular expression
  1542. * @string: the string to scan for matches
  1543. * @compile_options: compile options for the regular expression, or 0
  1544. * @match_options: match options, or 0
  1545. *
  1546. * Breaks the string on the pattern, and returns an array of
  1547. * the tokens. If the pattern contains capturing parentheses,
  1548. * then the text for each of the substrings will also be returned.
  1549. * If the pattern does not match anywhere in the string, then the
  1550. * whole string is returned as the first token.
  1551. *
  1552. * This function is equivalent to g_regex_split() but it does
  1553. * not require to compile the pattern with g_regex_new(), avoiding
  1554. * some lines of code when you need just to do a split without
  1555. * extracting substrings, capture counts, and so on.
  1556. *
  1557. * If this function is to be called on the same @pattern more than
  1558. * once, it's more efficient to compile the pattern once with
  1559. * g_regex_new() and then use g_regex_split().
  1560. *
  1561. * As a special case, the result of splitting the empty string ""
  1562. * is an empty vector, not a vector containing a single string.
  1563. * The reason for this special case is that being able to represent
  1564. * a empty vector is typically more useful than consistent handling
  1565. * of empty elements. If you do need to represent empty elements,
  1566. * you'll need to check for the empty string before calling this
  1567. * function.
  1568. *
  1569. * A pattern that can match empty strings splits @string into
  1570. * separate characters wherever it matches the empty string between
  1571. * characters. For example splitting "ab c" using as a separator
  1572. * "\s*", you will get "a", "b" and "c".
  1573. *
  1574. * Returns: a %NULL-terminated array of strings. Free it using g_strfreev()
  1575. *
  1576. * Since: 2.14
  1577. **/
  1578. gchar **
  1579. g_regex_split_simple (const gchar *pattern,
  1580. const gchar *string,
  1581. GRegexCompileFlags compile_options,
  1582. GRegexMatchFlags match_options)
  1583. {
  1584. GRegex *regex;
  1585. gchar **result;
  1586. regex = g_regex_new (pattern, compile_options, 0, NULL);
  1587. if (!regex)
  1588. return NULL;
  1589. result = g_regex_split_full (regex, string, -1, 0, match_options, 0, NULL);
  1590. g_regex_unref (regex);
  1591. return result;
  1592. }
  1593. /**
  1594. * g_regex_split:
  1595. * @regex: a #GRegex structure
  1596. * @string: the string to split with the pattern
  1597. * @match_options: match time option flags
  1598. *
  1599. * Breaks the string on the pattern, and returns an array of the tokens.
  1600. * If the pattern contains capturing parentheses, then the text for each
  1601. * of the substrings will also be returned. If the pattern does not match
  1602. * anywhere in the string, then the whole string is returned as the first
  1603. * token.
  1604. *
  1605. * As a special case, the result of splitting the empty string "" is an
  1606. * empty vector, not a vector containing a single string. The reason for
  1607. * this special case is that being able to represent a empty vector is
  1608. * typically more useful than consistent handling of empty elements. If
  1609. * you do need to represent empty elements, you'll need to check for the
  1610. * empty string before calling this function.
  1611. *
  1612. * A pattern that can match empty strings splits @string into separate
  1613. * characters wherever it matches the empty string between characters.
  1614. * For example splitting "ab c" using as a separator "\s*", you will get
  1615. * "a", "b" and "c".
  1616. *
  1617. * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
  1618. *
  1619. * Since: 2.14
  1620. **/
  1621. gchar **
  1622. g_regex_split (const GRegex *regex,
  1623. const gchar *string,
  1624. GRegexMatchFlags match_options)
  1625. {
  1626. return g_regex_split_full (regex, string, -1, 0,
  1627. match_options, 0, NULL);
  1628. }
  1629. /**
  1630. * g_regex_split_full:
  1631. * @regex: a #GRegex structure
  1632. * @string: the string to split with the pattern
  1633. * @string_len: the length of @string, or -1 if @string is nul-terminated
  1634. * @start_position: starting index of the string to match
  1635. * @match_options: match time option flags
  1636. * @max_tokens: the maximum number of tokens to split @string into.
  1637. * If this is less than 1, the string is split completely
  1638. * @error: return location for a #GError
  1639. *
  1640. * Breaks the string on the pattern, and returns an array of the tokens.
  1641. * If the pattern contains capturing parentheses, then the text for each
  1642. * of the substrings will also be returned. If the pattern does not match
  1643. * anywhere in the string, then the whole string is returned as the first
  1644. * token.
  1645. *
  1646. * As a special case, the result of splitting the empty string "" is an
  1647. * empty vector, not a vector containing a single string. The reason for
  1648. * this special case is that being able to represent a empty vector is
  1649. * typically more useful than consistent handling of empty elements. If
  1650. * you do need to represent empty elements, you'll need to check for the
  1651. * empty string before calling this function.
  1652. *
  1653. * A pattern that can match empty strings splits @string into separate
  1654. * characters wherever it matches the empty string between characters.
  1655. * For example splitting "ab c" using as a separator "\s*", you will get
  1656. * "a", "b" and "c".
  1657. *
  1658. * Setting @start_position differs from just passing over a shortened
  1659. * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
  1660. * that begins with any kind of lookbehind assertion, such as "\b".
  1661. *
  1662. * Returns: a %NULL-terminated gchar ** array. Free it using g_strfreev()
  1663. *
  1664. * Since: 2.14
  1665. **/
  1666. gchar **
  1667. g_regex_split_full (const GRegex *regex,
  1668. const gchar *string,
  1669. gssize string_len,
  1670. gint start_position,
  1671. GRegexMatchFlags match_options,
  1672. gint max_tokens,
  1673. GError **error)
  1674. {
  1675. GError *tmp_error = NULL;
  1676. GMatchInfo *match_info;
  1677. GList *list, *last;
  1678. gint i;
  1679. gint token_count;
  1680. gboolean match_ok;
  1681. /* position of the last separator. */
  1682. gint last_separator_end;
  1683. /* was the last match 0 bytes long? */
  1684. gboolean last_match_is_empty;
  1685. /* the returned array of char **s */
  1686. gchar **string_list;
  1687. g_return_val_if_fail (regex != NULL, NULL);
  1688. g_return_val_if_fail (string != NULL, NULL);
  1689. g_return_val_if_fail (start_position >= 0, NULL);
  1690. g_return_val_if_fail (error == NULL || *error == NULL, NULL);
  1691. g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
  1692. if (max_tokens <= 0)
  1693. max_tokens = G_MAXINT;
  1694. if (string_len < 0)
  1695. string_len = strlen (string);
  1696. /* zero-length string */
  1697. if (string_len - start_position == 0)
  1698. return g_new0 (gchar *, 1);
  1699. if (max_tokens == 1)
  1700. {
  1701. string_list = g_new0 (gchar *, 2);
  1702. string_list[0] = g_strndup (&string[start_position],
  1703. string_len - start_position);
  1704. return string_list;
  1705. }
  1706. list = NULL;
  1707. token_count = 0;
  1708. last_separator_end = start_position;
  1709. last_match_is_empty = FALSE;
  1710. match_ok = g_regex_match_full (regex, string, string_len, start_position,
  1711. match_options, &match_info, &tmp_error);
  1712. while (tmp_error == NULL)
  1713. {
  1714. if (match_ok)
  1715. {
  1716. last_match_is_empty =
  1717. (match_info->offsets[0] == match_info->offsets[1]);
  1718. /* we need to skip empty separators at the same position of the end
  1719. * of another separator. e.g. the string is "a b" and the separator
  1720. * is " *", so from 1 to 2 we have a match and at position 2 we have
  1721. * an empty match. */
  1722. if (last_separator_end != match_info->offsets[1])
  1723. {
  1724. gchar *token;
  1725. gint match_count;
  1726. token = g_strndup (string + last_separator_end,
  1727. match_info->offsets[0] - last_separator_end);
  1728. list = g_list_prepend (list, token);
  1729. token_count++;
  1730. /* if there were substrings, these need to be added to
  1731. * the list. */
  1732. match_count = g_match_info_get_match_count (match_info);
  1733. if (match_count > 1)
  1734. {
  1735. for (i = 1; i < match_count; i++)
  1736. list = g_list_prepend (list, g_match_info_fetch (match_info, i));
  1737. }
  1738. }
  1739. }
  1740. else
  1741. {
  1742. /* if there was no match, copy to end of string. */
  1743. if (!last_match_is_empty)
  1744. {
  1745. gchar *token = g_strndup (string + last_separator_end,
  1746. match_info->string_len - last_separator_end);
  1747. list = g_list_prepend (list, token);
  1748. }
  1749. /* no more tokens, end the loop. */
  1750. break;
  1751. }
  1752. /* -1 to leave room for the last part. */
  1753. if (token_count >= max_tokens - 1)
  1754. {
  1755. /* we have reached the maximum number of tokens, so we copy
  1756. * the remaining part of the string. */
  1757. if (last_match_is_empty)
  1758. {
  1759. /* the last match was empty, so we have moved one char
  1760. * after the real position to avoid empty matches at the
  1761. * same position. */
  1762. match_info->pos = PREV_CHAR (regex, &string[match_info->pos]) - string;
  1763. }
  1764. /* the if is needed in the case we have terminated the available
  1765. * tokens, but we are at the end of the string, so there are no
  1766. * characters left to copy. */
  1767. if (string_len > match_info->pos)
  1768. {
  1769. gchar *token = g_strndup (string + match_info->pos,
  1770. string_len - match_info->pos);
  1771. list = g_list_prepend (list, token);
  1772. }
  1773. /* end the loop. */
  1774. break;
  1775. }
  1776. last_separator_end = match_info->pos;
  1777. if (last_match_is_empty)
  1778. /* if the last match was empty, g_match_info_next() has moved
  1779. * forward to avoid infinite loops, but we still need to copy that
  1780. * character. */
  1781. last_separator_end = PREV_CHAR (regex, &string[last_separator_end]) - string;
  1782. match_ok = g_match_info_next (match_info, &tmp_error);
  1783. }
  1784. g_match_info_free (match_info);
  1785. if (tmp_error != NULL)
  1786. {
  1787. g_propagate_error (error, tmp_error);
  1788. g_list_foreach (list, (GFunc)g_free, NULL);
  1789. g_list_free (list);
  1790. match_info->pos = -1;
  1791. return NULL;
  1792. }
  1793. string_list = g_new (gchar *, g_list_length (list) + 1);
  1794. i = 0;
  1795. for (last = g_list_last (list); last; last = g_list_previous (last))
  1796. string_list[i++] = last->data;
  1797. string_list[i] = NULL;
  1798. g_list_free (list);
  1799. return string_list;
  1800. }
  1801. enum
  1802. {
  1803. REPL_TYPE_STRING,
  1804. REPL_TYPE_CHARACTER,
  1805. REPL_TYPE_SYMBOLIC_REFERENCE,
  1806. REPL_TYPE_NUMERIC_REFERENCE,
  1807. REPL_TYPE_CHANGE_CASE
  1808. };
  1809. typedef enum
  1810. {
  1811. CHANGE_CASE_NONE = 1 << 0,
  1812. CHANGE_CASE_UPPER = 1 << 1,
  1813. CHANGE_CASE_LOWER = 1 << 2,
  1814. CHANGE_CASE_UPPER_SINGLE = 1 << 3,
  1815. CHANGE_CASE_LOWER_SINGLE = 1 << 4,
  1816. CHANGE_CASE_SINGLE_MASK = CHANGE_CASE_UPPER_SINGLE | CHANGE_CASE_LOWER_SINGLE,
  1817. CHANGE_CASE_LOWER_MASK = CHANGE_CASE_LOWER | CHANGE_CASE_LOWER_SINGLE,
  1818. CHANGE_CASE_UPPER_MASK = CHANGE_CASE_UPPER | CHANGE_CASE_UPPER_SINGLE
  1819. } ChangeCase;
  1820. struct _InterpolationData
  1821. {
  1822. gchar *text;
  1823. gint type;
  1824. gint num;
  1825. gchar c;
  1826. ChangeCase change_case;
  1827. };
  1828. static void
  1829. free_interpolation_data (InterpolationData *data)
  1830. {
  1831. g_free (data->text);
  1832. g_free (data);
  1833. }
  1834. static const gchar *
  1835. expand_escape (const gchar *replacement,
  1836. const gchar *p,
  1837. InterpolationData *data,
  1838. GError **error)
  1839. {
  1840. const gchar *q, *r;
  1841. gint x, d, h, i;
  1842. const gchar *error_detail;
  1843. gint base = 0;
  1844. GError *tmp_error = NULL;
  1845. p++;
  1846. switch (*p)
  1847. {
  1848. case 't':
  1849. p++;
  1850. data->c = '\t';
  1851. data->type = REPL_TYPE_CHARACTER;
  1852. break;
  1853. case 'n':
  1854. p++;
  1855. data->c = '\n';
  1856. data->type = REPL_TYPE_CHARACTER;
  1857. break;
  1858. case 'v':
  1859. p++;
  1860. data->c = '\v';
  1861. data->type = REPL_TYPE_CHARACTER;
  1862. break;
  1863. case 'r':
  1864. p++;
  1865. data->c = '\r';
  1866. data->type = REPL_TYPE_CHARACTER;
  1867. break;
  1868. case 'f':
  1869. p++;
  1870. data->c = '\f';
  1871. data->type = REPL_TYPE_CHARACTER;
  1872. break;
  1873. case 'a':
  1874. p++;
  1875. data->c = '\a';
  1876. data->type = REPL_TYPE_CHARACTER;
  1877. break;
  1878. case 'b':
  1879. p++;
  1880. data->c = '\b';
  1881. data->type = REPL_TYPE_CHARACTER;
  1882. break;
  1883. case '\\':
  1884. p++;
  1885. data->c = '\\';
  1886. data->type = REPL_TYPE_CHARACTER;
  1887. break;
  1888. case 'x':
  1889. p++;
  1890. x = 0;
  1891. if (*p == '{')
  1892. {
  1893. p++;
  1894. do
  1895. {
  1896. h = g_ascii_xdigit_value (*p);
  1897. if (h < 0)
  1898. {
  1899. error_detail = "hexadecimal digit or '}' expected";
  1900. goto error;
  1901. }
  1902. x = x * 16 + h;
  1903. p++;
  1904. }
  1905. while (*p != '}');
  1906. p++;
  1907. }
  1908. else
  1909. {
  1910. for (i = 0; i < 2; i++)
  1911. {
  1912. h = g_ascii_xdigit_value (*p);
  1913. if (h < 0)
  1914. {
  1915. error_detail = "hexadecimal digit expected";
  1916. goto error;
  1917. }
  1918. x = x * 16 + h;
  1919. p++;
  1920. }
  1921. }
  1922. data->type = REPL_TYPE_STRING;
  1923. data->text = g_new0 (gchar, 8);
  1924. g_unichar_to_utf8 (x, data->text);
  1925. break;
  1926. case 'l':
  1927. p++;
  1928. data->type = REPL_TYPE_CHANGE_CASE;
  1929. data->change_case = CHANGE_CASE_LOWER_SINGLE;
  1930. break;
  1931. case 'u':
  1932. p++;
  1933. data->type = REPL_TYPE_CHANGE_CASE;
  1934. data->change_case = CHANGE_CASE_UPPER_SINGLE;
  1935. break;
  1936. case 'L':
  1937. p++;
  1938. data->type = REPL_TYPE_CHANGE_CASE;
  1939. data->change_case = CHANGE_CASE_LOWER;
  1940. break;
  1941. case 'U':
  1942. p++;
  1943. data->type = REPL_TYPE_CHANGE_CASE;
  1944. data->change_case = CHANGE_CASE_UPPER;
  1945. break;
  1946. case 'E':
  1947. p++;
  1948. data->type = REPL_TYPE_CHANGE_CASE;
  1949. data->change_case = CHANGE_CASE_NONE;
  1950. break;
  1951. case 'g':
  1952. p++;
  1953. if (*p != '<')
  1954. {
  1955. error_detail = "missing '<' in symbolic reference";
  1956. goto error;
  1957. }
  1958. q = p + 1;
  1959. do
  1960. {
  1961. p++;
  1962. if (!*p)
  1963. {
  1964. error_detail = "unfinished symbolic reference";
  1965. goto error;
  1966. }
  1967. }
  1968. while (*p != '>');
  1969. if (p - q == 0)
  1970. {
  1971. error_detail = "zero-length symbolic reference";
  1972. goto error;
  1973. }
  1974. if (g_ascii_isdigit (*q))
  1975. {
  1976. x = 0;
  1977. do
  1978. {
  1979. h = g_ascii_digit_value (*q);
  1980. if (h < 0)
  1981. {
  1982. error_detail = "digit expected";
  1983. p = q;
  1984. goto error;
  1985. }
  1986. x = x * 10 + h;
  1987. q++;
  1988. }
  1989. while (q != p);
  1990. data->num = x;
  1991. data->type = REPL_TYPE_NUMERIC_REFERENCE;
  1992. }
  1993. else
  1994. {
  1995. r = q;
  1996. do
  1997. {
  1998. if (!g_ascii_isalnum (*r))
  1999. {
  2000. error_detail = "illegal symbolic reference";
  2001. p = r;
  2002. goto error;
  2003. }
  2004. r++;
  2005. }
  2006. while (r != p);
  2007. data->text = g_strndup (q, p - q);
  2008. data->type = REPL_TYPE_SYMBOLIC_REFERENCE;
  2009. }
  2010. p++;
  2011. break;
  2012. case '0':
  2013. /* if \0 is followed by a number is an octal number representing a
  2014. * character, else it is a numeric reference. */
  2015. if (g_ascii_digit_value (*g_utf8_next_char (p)) >= 0)
  2016. {
  2017. base = 8;
  2018. p = g_utf8_next_char (p);
  2019. }
  2020. case '1':
  2021. case '2':
  2022. case '3':
  2023. case '4':
  2024. case '5':
  2025. case '6':
  2026. case '7':
  2027. case '8':
  2028. case '9':
  2029. x = 0;
  2030. d = 0;
  2031. for (i = 0; i < 3; i++)
  2032. {
  2033. h = g_ascii_digit_value (*p);
  2034. if (h < 0)
  2035. break;
  2036. if (h > 7)
  2037. {
  2038. if (base == 8)
  2039. break;
  2040. else
  2041. base = 10;
  2042. }
  2043. if (i == 2 && base == 10)
  2044. break;
  2045. x = x * 8 + h;
  2046. d = d * 10 + h;
  2047. p++;
  2048. }
  2049. if (base == 8 || i == 3)
  2050. {
  2051. data->type = REPL_TYPE_STRING;
  2052. data->text = g_new0 (gchar, 8);
  2053. g_unichar_to_utf8 (x, data->text);
  2054. }
  2055. else
  2056. {
  2057. data->type = REPL_TYPE_NUMERIC_REFERENCE;
  2058. data->num = d;
  2059. }
  2060. break;
  2061. case 0:
  2062. error_detail = "stray final '\\'";
  2063. goto error;
  2064. break;
  2065. default:
  2066. error_detail = "unknown escape sequence";
  2067. goto error;
  2068. }
  2069. return p;
  2070. error:
  2071. /* G_GSSIZE_FORMAT doesn't work with gettext, so we use %lu */
  2072. tmp_error = g_error_new (G_REGEX_ERROR,
  2073. G_REGEX_ERROR_REPLACE,
  2074. "Error while parsing replacement "
  2075. "text \"%s\" at char %lu: %s",
  2076. replacement,
  2077. (gulong)(p - replacement),
  2078. error_detail);
  2079. g_propagate_error (error, tmp_error);
  2080. return NULL;
  2081. }
  2082. static GList *
  2083. split_replacement (const gchar *replacement,
  2084. GError **error)
  2085. {
  2086. GList *list = NULL;
  2087. InterpolationData *data;
  2088. const gchar *p, *start;
  2089. start = p = replacement;
  2090. while (*p)
  2091. {
  2092. if (*p == '\\')
  2093. {
  2094. data = g_new0 (InterpolationData, 1);
  2095. start = p = expand_escape (replacement, p, data, error);
  2096. if (p == NULL)
  2097. {
  2098. g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
  2099. g_list_free (list);
  2100. free_interpolation_data (data);
  2101. return NULL;
  2102. }
  2103. list = g_list_prepend (list, data);
  2104. }
  2105. else
  2106. {
  2107. p++;
  2108. if (*p == '\\' || *p == '\0')
  2109. {
  2110. if (p - start > 0)
  2111. {
  2112. data = g_new0 (InterpolationData, 1);
  2113. data->text = g_strndup (start, p - start);
  2114. data->type = REPL_TYPE_STRING;
  2115. list = g_list_prepend (list, data);
  2116. }
  2117. }
  2118. }
  2119. }
  2120. return g_list_reverse (list);
  2121. }
  2122. /* Change the case of c based on change_case. */
  2123. #define CHANGE_CASE(c, change_case) \
  2124. (((change_case) & CHANGE_CASE_LOWER_MASK) ? \
  2125. g_unichar_tolower (c) : \
  2126. g_unichar_toupper (c))
  2127. static void
  2128. string_append (GString *string,
  2129. const gchar *text,
  2130. ChangeCase *change_case)
  2131. {
  2132. gunichar c;
  2133. if (text[0] == '\0')
  2134. return;
  2135. if (*change_case == CHANGE_CASE_NONE)
  2136. {
  2137. g_string_append (string, text);
  2138. }
  2139. else if (*change_case & CHANGE_CASE_SINGLE_MASK)
  2140. {
  2141. c = g_utf8_get_char (text);
  2142. g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
  2143. g_string_append (string, g_utf8_next_char (text));
  2144. *change_case = CHANGE_CASE_NONE;
  2145. }
  2146. else
  2147. {
  2148. while (*text != '\0')
  2149. {
  2150. c = g_utf8_get_char (text);
  2151. g_string_append_unichar (string, CHANGE_CASE (c, *change_case));
  2152. text = g_utf8_next_char (text);
  2153. }
  2154. }
  2155. }
  2156. static gboolean
  2157. interpolate_replacement (const GMatchInfo *match_info,
  2158. GString *result,
  2159. gpointer data)
  2160. {
  2161. GList *list;
  2162. InterpolationData *idata;
  2163. gchar *match;
  2164. ChangeCase change_case = CHANGE_CASE_NONE;
  2165. for (list = data; list; list = list->next)
  2166. {
  2167. idata = list->data;
  2168. switch (idata->type)
  2169. {
  2170. case REPL_TYPE_STRING:
  2171. string_append (result, idata->text, &change_case);
  2172. break;
  2173. case REPL_TYPE_CHARACTER:
  2174. g_string_append_c (result, CHANGE_CASE (idata->c, change_case));
  2175. if (change_case & CHANGE_CASE_SINGLE_MASK)
  2176. change_case = CHANGE_CASE_NONE;
  2177. break;
  2178. case REPL_TYPE_NUMERIC_REFERENCE:
  2179. match = g_match_info_fetch (match_info, idata->num);
  2180. if (match)
  2181. {
  2182. string_append (result, match, &change_case);
  2183. g_free (match);
  2184. }
  2185. break;
  2186. case REPL_TYPE_SYMBOLIC_REFERENCE:
  2187. match = g_match_info_fetch_named (match_info, idata->text);
  2188. if (match)
  2189. {
  2190. string_append (result, match, &change_case);
  2191. g_free (match);
  2192. }
  2193. break;
  2194. case REPL_TYPE_CHANGE_CASE:
  2195. change_case = idata->change_case;
  2196. break;
  2197. }
  2198. }
  2199. return FALSE;
  2200. }
  2201. /* whether actual match_info is needed for replacement, i.e.
  2202. * whether there are references
  2203. */
  2204. static gboolean
  2205. interpolation_list_needs_match (GList *list)
  2206. {
  2207. while (list != NULL)
  2208. {
  2209. InterpolationData *data = list->data;
  2210. if (data->type == REPL_TYPE_SYMBOLIC_REFERENCE ||
  2211. data->type == REPL_TYPE_NUMERIC_REFERENCE)
  2212. {
  2213. return TRUE;
  2214. }
  2215. list = list->next;
  2216. }
  2217. return FALSE;
  2218. }
  2219. /**
  2220. * g_regex_replace:
  2221. * @regex: a #GRegex structure
  2222. * @string: the string to perform matches against
  2223. * @string_len: the length of @string, or -1 if @string is nul-terminated
  2224. * @start_position: starting index of the string to match
  2225. * @replacement: text to replace each match with
  2226. * @match_options: options for the match
  2227. * @error: location to store the error occuring, or %NULL to ignore errors
  2228. *
  2229. * Replaces all occurrences of the pattern in @regex with the
  2230. * replacement text. Backreferences of the form '\number' or
  2231. * '\g&lt;number&gt;' in the replacement text are interpolated by the
  2232. * number-th captured subexpression of the match, '\g&lt;name&gt;' refers
  2233. * to the captured subexpression with the given name. '\0' refers to the
  2234. * complete match, but '\0' followed by a number is the octal representation
  2235. * of a character. To include a literal '\' in the replacement, write '\\'.
  2236. * There are also escapes that changes the case of the following text:
  2237. *
  2238. * <variablelist>
  2239. * <varlistentry><term>\l</term>
  2240. * <listitem>
  2241. * <para>Convert to lower case the next character</para>
  2242. * </listitem>
  2243. * </varlistentry>
  2244. * <varlistentry><term>\u</term>
  2245. * <listitem>
  2246. * <para>Convert to upper case the next character</para>
  2247. * </listitem>
  2248. * </varlistentry>
  2249. * <varlistentry><term>\L</term>
  2250. * <listitem>
  2251. * <para>Convert to lower case till \E</para>
  2252. * </listitem>
  2253. * </varlistentry>
  2254. * <varlistentry><term>\U</term>
  2255. * <listitem>
  2256. * <para>Convert to upper case till \E</para>
  2257. * </listitem>
  2258. * </varlistentry>
  2259. * <varlistentry><term>\E</term>
  2260. * <listitem>
  2261. * <para>End case modification</para>
  2262. * </listitem>
  2263. * </varlistentry>
  2264. * </variablelist>
  2265. *
  2266. * If you do not need to use backreferences use g_regex_replace_literal().
  2267. *
  2268. * The @replacement string must be UTF-8 encoded even if #G_REGEX_RAW was
  2269. * passed to g_regex_new(). If you want to use not UTF-8 encoded stings
  2270. * you can use g_regex_replace_literal().
  2271. *
  2272. * Setting @start_position differs from just passing over a shortened
  2273. * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern that
  2274. * begins with any kind of lookbehind assertion, such as "\b".
  2275. *
  2276. * Returns: a newly allocated string containing the replacements
  2277. *
  2278. * Since: 2.14
  2279. */
  2280. gchar *
  2281. g_regex_replace (const GRegex *regex,
  2282. const gchar *string,
  2283. gssize string_len,
  2284. gint start_position,
  2285. const gchar *replacement,
  2286. GRegexMatchFlags match_options,
  2287. GError **error)
  2288. {
  2289. gchar *result;
  2290. GList *list;
  2291. GError *tmp_error = NULL;
  2292. g_return_val_if_fail (regex != NULL, NULL);
  2293. g_return_val_if_fail (string != NULL, NULL);
  2294. g_return_val_if_fail (start_position >= 0, NULL);
  2295. g_return_val_if_fail (replacement != NULL, NULL);
  2296. g_return_val_if_fail (error == NULL || *error == NULL, NULL);
  2297. g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
  2298. list = split_replacement (replacement, &tmp_error);
  2299. if (tmp_error != NULL)
  2300. {
  2301. g_propagate_error (error, tmp_error);
  2302. return NULL;
  2303. }
  2304. result = g_regex_replace_eval (regex,
  2305. string, string_len, start_position,
  2306. match_options,
  2307. interpolate_replacement,
  2308. (gpointer)list,
  2309. &tmp_error);
  2310. if (tmp_error != NULL)
  2311. g_propagate_error (error, tmp_error);
  2312. g_list_foreach (list, (GFunc)free_interpolation_data, NULL);
  2313. g_list_free (list);
  2314. return result;
  2315. }
  2316. static gboolean
  2317. literal_replacement (const GMatchInfo *match_info,
  2318. GString *result,
  2319. gpointer data)
  2320. {
  2321. g_string_append (result, data);
  2322. return FALSE;
  2323. }
  2324. /**
  2325. * g_regex_replace_literal:
  2326. * @regex: a #GRegex structure
  2327. * @string: the string to perform matches against
  2328. * @string_len: the length of @string, or -1 if @string is nul-terminated
  2329. * @start_position: starting index of the string to match
  2330. * @replacement: text to replace each match with
  2331. * @match_options: options for the match
  2332. * @error: location to store the error occuring, or %NULL to ignore errors
  2333. *
  2334. * Replaces all occurrences of the pattern in @regex with the
  2335. * replacement text. @replacement is replaced literally, to
  2336. * include backreferences use g_regex_replace().
  2337. *
  2338. * Setting @start_position differs from just passing over a
  2339. * shortened string and setting #G_REGEX_MATCH_NOTBOL in the
  2340. * case of a pattern that begins with any kind of lookbehind
  2341. * assertion, such as "\b".
  2342. *
  2343. * Returns: a newly allocated string containing the replacements
  2344. *
  2345. * Since: 2.14
  2346. */
  2347. gchar *
  2348. g_regex_replace_literal (const GRegex *regex,
  2349. const gchar *string,
  2350. gssize string_len,
  2351. gint start_position,
  2352. const gchar *replacement,
  2353. GRegexMatchFlags match_options,
  2354. GError **error)
  2355. {
  2356. g_return_val_if_fail (replacement != NULL, NULL);
  2357. g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
  2358. return g_regex_replace_eval (regex,
  2359. string, string_len, start_position,
  2360. match_options,
  2361. literal_replacement,
  2362. (gpointer)replacement,
  2363. error);
  2364. }
  2365. /**
  2366. * g_regex_replace_eval:
  2367. * @regex: a #GRegex structure from g_regex_new()
  2368. * @string: string to perform matches against
  2369. * @string_len: the length of @string, or -1 if @string is nul-terminated
  2370. * @start_position: starting index of the string to match
  2371. * @match_options: options for the match
  2372. * @eval: a function to call for each match
  2373. * @user_data: user data to pass to the function
  2374. * @error: location to store the error occuring, or %NULL to ignore errors
  2375. *
  2376. * Replaces occurrences of the pattern in regex with the output of
  2377. * @eval for that occurrence.
  2378. *
  2379. * Setting @start_position differs from just passing over a shortened
  2380. * string and setting #G_REGEX_MATCH_NOTBOL in the case of a pattern
  2381. * that begins with any kind of lookbehind assertion, such as "\b".
  2382. *
  2383. * The following example uses g_regex_replace_eval() to replace multiple
  2384. * strings at once:
  2385. * |[
  2386. * static gboolean
  2387. * eval_cb (const GMatchInfo *info,
  2388. * GString *res,
  2389. * gpointer data)
  2390. * {
  2391. * gchar *match;
  2392. * gchar *r;
  2393. *
  2394. * match = g_match_info_fetch (info, 0);
  2395. * r = g_hash_table_lookup ((GHashTable *)data, match);
  2396. * g_string_append (res, r);
  2397. * g_free (match);
  2398. *
  2399. * return FALSE;
  2400. * }
  2401. *
  2402. * /&ast; ... &ast;/
  2403. *
  2404. * GRegex *reg;
  2405. * GHashTable *h;
  2406. * gchar *res;
  2407. *
  2408. * h = g_hash_table_new (g_str_hash, g_str_equal);
  2409. *
  2410. * g_hash_table_insert (h, "1", "ONE");
  2411. * g_hash_table_insert (h, "2", "TWO");
  2412. * g_hash_table_insert (h, "3", "THREE");
  2413. * g_hash_table_insert (h, "4", "FOUR");
  2414. *
  2415. * reg = g_regex_new ("1|2|3|4", 0, 0, NULL);
  2416. * res = g_regex_replace_eval (reg, text, -1, 0, 0, eval_cb, h, NULL);
  2417. * g_hash_table_destroy (h);
  2418. *
  2419. * /&ast; ... &ast;/
  2420. * ]|
  2421. *
  2422. * Returns: a newly allocated string containing the replacements
  2423. *
  2424. * Since: 2.14
  2425. */
  2426. gchar *
  2427. g_regex_replace_eval (const GRegex *regex,
  2428. const gchar *string,
  2429. gssize string_len,
  2430. gint start_position,
  2431. GRegexMatchFlags match_options,
  2432. GRegexEvalCallback eval,
  2433. gpointer user_data,
  2434. GError **error)
  2435. {
  2436. GMatchInfo *match_info;
  2437. GString *result;
  2438. gint str_pos = 0;
  2439. gboolean done = FALSE;
  2440. GError *tmp_error = NULL;
  2441. g_return_val_if_fail (regex != NULL, NULL);
  2442. g_return_val_if_fail (string != NULL, NULL);
  2443. g_return_val_if_fail (start_position >= 0, NULL);
  2444. g_return_val_if_fail (eval != NULL, NULL);
  2445. g_return_val_if_fail ((match_options & ~G_REGEX_MATCH_MASK) == 0, NULL);
  2446. if (string_len < 0)
  2447. string_len = strlen (string);
  2448. result = g_string_sized_new (string_len);
  2449. /* run down the string making matches. */
  2450. g_regex_match_full (regex, string, string_len, start_position,
  2451. match_options, &match_info, &tmp_error);
  2452. while (!done && g_match_info_matches (match_info))
  2453. {
  2454. g_string_append_len (result,
  2455. string + str_pos,
  2456. match_info->offsets[0] - str_pos);
  2457. done = (*eval) (match_info, result, user_data);
  2458. str_pos = match_info->offsets[1];
  2459. g_match_info_next (match_info, &tmp_error);
  2460. }
  2461. g_match_info_free (match_info);
  2462. if (tmp_error != NULL)
  2463. {
  2464. g_propagate_error (error, tmp_error);
  2465. g_string_free (result, TRUE);
  2466. return NULL;
  2467. }
  2468. g_string_append_len (result, string + str_pos, string_len - str_pos);
  2469. return g_string_free (result, FALSE);
  2470. }
  2471. /**
  2472. * g_regex_check_replacement:
  2473. * @replacement: the replacement string
  2474. * @has_references: location to store information about
  2475. * references in @replacement or %NULL
  2476. * @error: location to store error
  2477. *
  2478. * Checks whether @replacement is a valid replacement string
  2479. * (see g_regex_replace()), i.e. that all escape sequences in
  2480. * it are valid.
  2481. *
  2482. * If @has_references is not %NULL then @replacement is checked
  2483. * for pattern references. For instance, replacement text 'foo\n'
  2484. * does not contain references and may be evaluated without information
  2485. * about actual match, but '\0\1' (whole match followed by first
  2486. * subpattern) requires valid #GMatchInfo object.
  2487. *
  2488. * Returns: whether @replacement is a valid replacement string
  2489. *
  2490. * Since: 2.14
  2491. */
  2492. gboolean
  2493. g_regex_check_replacement (const gchar *replacement,
  2494. gboolean *has_references,
  2495. GError **error)
  2496. {
  2497. GList *list;
  2498. GError *tmp = NULL;
  2499. list = split_replacement (replacement, &tmp);
  2500. if (tmp)
  2501. {
  2502. g_propagate_error (error, tmp);
  2503. return FALSE;
  2504. }
  2505. if (has_references)
  2506. *has_references = interpolation_list_needs_match (list);
  2507. g_list_foreach (list, (GFunc) free_interpolation_data, NULL);
  2508. g_list_free (list);
  2509. return TRUE;
  2510. }
  2511. /**
  2512. * g_regex_escape_string:
  2513. * @string: the string to escape
  2514. * @length: the length of @string, or -1 if @string is nul-terminated
  2515. *
  2516. * Escapes the special characters used for regular expressions
  2517. * in @string, for instance "a.b*c" becomes "a\.b\*c". This
  2518. * function is useful to dynamically generate regular expressions.
  2519. *
  2520. * @string can contain nul characters that are replaced with "\0",
  2521. * in this case remember to specify the correct length of @string
  2522. * in @length.
  2523. *
  2524. * Returns: a newly-allocated escaped string
  2525. *
  2526. * Since: 2.14
  2527. */
  2528. gchar *
  2529. g_regex_escape_string (const gchar *string,
  2530. gint length)
  2531. {
  2532. GString *escaped;
  2533. const char *p, *piece_start, *end;
  2534. g_return_val_if_fail (string != NULL, NULL);
  2535. if (length < 0)
  2536. length = strlen (string);
  2537. end = string + length;
  2538. p = piece_start = string;
  2539. escaped = g_string_sized_new (length + 1);
  2540. while (p < end)
  2541. {
  2542. switch (*p)
  2543. {
  2544. case '\0':
  2545. case '\\':
  2546. case '|':
  2547. case '(':
  2548. case ')':
  2549. case '[':
  2550. case ']':
  2551. case '{':
  2552. case '}':
  2553. case '^':
  2554. case '$':
  2555. case '*':
  2556. case '+':
  2557. case '?':
  2558. case '.':
  2559. if (p != piece_start)
  2560. /* copy the previous piece. */
  2561. g_string_append_len (escaped, piece_start, p - piece_start);
  2562. g_string_append_c (escaped, '\\');
  2563. if (*p == '\0')
  2564. g_string_append_c (escaped, '0');
  2565. else
  2566. g_string_append_c (escaped, *p);
  2567. piece_start = ++p;
  2568. break;
  2569. default:
  2570. p = g_utf8_next_char (p);
  2571. break;
  2572. }
  2573. }
  2574. if (piece_start < end)
  2575. g_string_append_len (escaped, piece_start, end - piece_start);
  2576. return g_string_free (escaped, FALSE);
  2577. }