DESCRIPTION.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. Parse strings using a specification based on the Python format() syntax.
  2. ``parse()`` is the opposite of ``format()``
  3. The module is set up to only export ``parse()``, ``search()``, ``findall()``,
  4. and ``with_pattern()`` when ``import \*`` is used:
  5. >>> from parse import *
  6. >From there it's a simple thing to parse a string:
  7. >>> parse("It's {}, I love it!", "It's spam, I love it!")
  8. <Result ('spam',) {}>
  9. >>> _[0]
  10. 'spam'
  11. Or to search a string for some pattern:
  12. >>> search('Age: {:d}\n', 'Name: Rufus\nAge: 42\nColor: red\n')
  13. <Result (42,) {}>
  14. Or find all the occurrences of some pattern in a string:
  15. >>> ''.join(r.fixed[0] for r in findall(">{}<", "<p>the <b>bold</b> text</p>"))
  16. 'the bold text'
  17. If you're going to use the same pattern to match lots of strings you can
  18. compile it once:
  19. >>> from parse import compile
  20. >>> p = compile("It's {}, I love it!")
  21. >>> print(p)
  22. <Parser "It's {}, I love it!">
  23. >>> p.parse("It's spam, I love it!")
  24. <Result ('spam',) {}>
  25. ("compile" is not exported for ``import *`` usage as it would override the
  26. built-in ``compile()`` function)
  27. The default behaviour is to match strings case insensitively. You may match with
  28. case by specifying `case_sensitive=True`:
  29. >>> parse('SPAM', 'spam', case_sensitive=True) is None
  30. True
  31. Format Syntax
  32. -------------
  33. A basic version of the `Format String Syntax`_ is supported with anonymous
  34. (fixed-position), named and formatted fields::
  35. {[field name]:[format spec]}
  36. Field names must be a valid Python identifiers, including dotted names;
  37. element indexes imply dictionaries (see below for example).
  38. Numbered fields are also not supported: the result of parsing will include
  39. the parsed fields in the order they are parsed.
  40. The conversion of fields to types other than strings is done based on the
  41. type in the format specification, which mirrors the ``format()`` behaviour.
  42. There are no "!" field conversions like ``format()`` has.
  43. Some simple parse() format string examples:
  44. >>> parse("Bring me a {}", "Bring me a shrubbery")
  45. <Result ('shrubbery',) {}>
  46. >>> r = parse("The {} who say {}", "The knights who say Ni!")
  47. >>> print(r)
  48. <Result ('knights', 'Ni!') {}>
  49. >>> print(r.fixed)
  50. ('knights', 'Ni!')
  51. >>> r = parse("Bring out the holy {item}", "Bring out the holy hand grenade")
  52. >>> print(r)
  53. <Result () {'item': 'hand grenade'}>
  54. >>> print(r.named)
  55. {'item': 'hand grenade'}
  56. >>> print(r['item'])
  57. hand grenade
  58. >>> 'item' in r
  59. True
  60. Note that `in` only works if you have named fields. Dotted names and indexes
  61. are possible though the application must make additional sense of the result:
  62. >>> r = parse("Mmm, {food.type}, I love it!", "Mmm, spam, I love it!")
  63. >>> print(r)
  64. <Result () {'food.type': 'spam'}>
  65. >>> print(r.named)
  66. {'food.type': 'spam'}
  67. >>> print(r['food.type'])
  68. spam
  69. >>> r = parse("My quest is {quest[name]}", "My quest is to seek the holy grail!")
  70. >>> print(r)
  71. <Result () {'quest': {'name': 'to seek the holy grail!'}}>
  72. >>> print(r['quest'])
  73. {'name': 'to seek the holy grail!'}
  74. >>> print(r['quest']['name'])
  75. to seek the holy grail!
  76. If the text you're matching has braces in it you can match those by including
  77. a double-brace ``{{`` or ``}}`` in your format string, just like format() does.
  78. Format Specification
  79. --------------------
  80. Most often a straight format-less ``{}`` will suffice where a more complex
  81. format specification might have been used.
  82. Most of `format()`'s `Format Specification Mini-Language`_ is supported:
  83. [[fill]align][0][width][.precision][type]
  84. The differences between `parse()` and `format()` are:
  85. - The align operators will cause spaces (or specified fill character) to be
  86. stripped from the parsed value. The width is not enforced; it just indicates
  87. there may be whitespace or "0"s to strip.
  88. - Numeric parsing will automatically handle a "0b", "0o" or "0x" prefix.
  89. That is, the "#" format character is handled automatically by d, b, o
  90. and x formats. For "d" any will be accepted, but for the others the correct
  91. prefix must be present if at all.
  92. - Numeric sign is handled automatically.
  93. - The thousands separator is handled automatically if the "n" type is used.
  94. - The types supported are a slightly different mix to the format() types. Some
  95. format() types come directly over: "d", "n", "%", "f", "e", "b", "o" and "x".
  96. In addition some regular expression character group types "D", "w", "W", "s"
  97. and "S" are also available.
  98. - The "e" and "g" types are case-insensitive so there is not need for
  99. the "E" or "G" types.
  100. ===== =========================================== ========
  101. Type Characters Matched Output
  102. ===== =========================================== ========
  103. l Letters (ASCII) str
  104. w Letters, numbers and underscore str
  105. W Not letters, numbers and underscore str
  106. s Whitespace str
  107. S Non-whitespace str
  108. d Digits (effectively integer numbers) int
  109. D Non-digit str
  110. n Numbers with thousands separators (, or .) int
  111. % Percentage (converted to value/100.0) float
  112. f Fixed-point numbers float
  113. F Decimal numbers Decimal
  114. e Floating-point numbers with exponent float
  115. e.g. 1.1e-10, NAN (all case insensitive)
  116. g General number format (either d, f or e) float
  117. b Binary numbers int
  118. o Octal numbers int
  119. x Hexadecimal numbers (lower and upper case) int
  120. ti ISO 8601 format date/time datetime
  121. e.g. 1972-01-20T10:21:36Z ("T" and "Z"
  122. optional)
  123. te RFC2822 e-mail format date/time datetime
  124. e.g. Mon, 20 Jan 1972 10:21:36 +1000
  125. tg Global (day/month) format date/time datetime
  126. e.g. 20/1/1972 10:21:36 AM +1:00
  127. ta US (month/day) format date/time datetime
  128. e.g. 1/20/1972 10:21:36 PM +10:30
  129. tc ctime() format date/time datetime
  130. e.g. Sun Sep 16 01:03:52 1973
  131. th HTTP log format date/time datetime
  132. e.g. 21/Nov/2011:00:07:11 +0000
  133. ts Linux system log format date/time datetime
  134. e.g. Nov 9 03:37:44
  135. tt Time time
  136. e.g. 10:21:36 PM -5:30
  137. ===== =========================================== ========
  138. Some examples of typed parsing with ``None`` returned if the typing
  139. does not match:
  140. >>> parse('Our {:d} {:w} are...', 'Our 3 weapons are...')
  141. <Result (3, 'weapons') {}>
  142. >>> parse('Our {:d} {:w} are...', 'Our three weapons are...')
  143. >>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM')
  144. <Result (datetime.datetime(2011, 2, 1, 23, 0),) {}>
  145. And messing about with alignment:
  146. >>> parse('with {:>} herring', 'with a herring')
  147. <Result ('a',) {}>
  148. >>> parse('spam {:^} spam', 'spam lovely spam')
  149. <Result ('lovely',) {}>
  150. Note that the "center" alignment does not test to make sure the value is
  151. centered - it just strips leading and trailing whitespace.
  152. Width and precision may be used to restrict the size of matched text
  153. from the input. Width specifies a minimum size and precision specifies
  154. a maximum. For example:
  155. >>> parse('{:.2}{:.2}', 'look') # specifying precision
  156. <Result ('lo', 'ok') {}>
  157. >>> parse('{:4}{:4}', 'look at that') # specifying width
  158. <Result ('look', 'at that') {}>
  159. >>> parse('{:4}{:.4}', 'look at that') # specifying both
  160. <Result ('look at ', 'that') {}>
  161. >>> parse('{:2d}{:2d}', '0440') # parsing two contiguous numbers
  162. <Result (4, 40) {}>
  163. Some notes for the date and time types:
  164. - the presence of the time part is optional (including ISO 8601, starting
  165. at the "T"). A full datetime object will always be returned; the time
  166. will be set to 00:00:00. You may also specify a time without seconds.
  167. - when a seconds amount is present in the input fractions will be parsed
  168. to give microseconds.
  169. - except in ISO 8601 the day and month digits may be 0-padded.
  170. - the date separator for the tg and ta formats may be "-" or "/".
  171. - named months (abbreviations or full names) may be used in the ta and tg
  172. formats in place of numeric months.
  173. - as per RFC 2822 the e-mail format may omit the day (and comma), and the
  174. seconds but nothing else.
  175. - hours greater than 12 will be happily accepted.
  176. - the AM/PM are optional, and if PM is found then 12 hours will be added
  177. to the datetime object's hours amount - even if the hour is greater
  178. than 12 (for consistency.)
  179. - in ISO 8601 the "Z" (UTC) timezone part may be a numeric offset
  180. - timezones are specified as "+HH:MM" or "-HH:MM". The hour may be one or two
  181. digits (0-padded is OK.) Also, the ":" is optional.
  182. - the timezone is optional in all except the e-mail format (it defaults to
  183. UTC.)
  184. - named timezones are not handled yet.
  185. Note: attempting to match too many datetime fields in a single parse() will
  186. currently result in a resource allocation issue. A TooManyFields exception
  187. will be raised in this instance. The current limit is about 15. It is hoped
  188. that this limit will be removed one day.
  189. .. _`Format String Syntax`:
  190. http://docs.python.org/library/string.html#format-string-syntax
  191. .. _`Format Specification Mini-Language`:
  192. http://docs.python.org/library/string.html#format-specification-mini-language
  193. Result and Match Objects
  194. ------------------------
  195. The result of a ``parse()`` and ``search()`` operation is either ``None`` (no match), a
  196. ``Result`` instance or a ``Match`` instance if ``evaluate_result`` is False.
  197. The ``Result`` instance has three attributes:
  198. fixed
  199. A tuple of the fixed-position, anonymous fields extracted from the input.
  200. named
  201. A dictionary of the named fields extracted from the input.
  202. spans
  203. A dictionary mapping the names and fixed position indices matched to a
  204. 2-tuple slice range of where the match occurred in the input.
  205. The span does not include any stripped padding (alignment or width).
  206. The ``Match`` instance has one method:
  207. evaluate_result()
  208. Generates and returns a ``Result`` instance for this ``Match`` object.
  209. Custom Type Conversions
  210. -----------------------
  211. If you wish to have matched fields automatically converted to your own type you
  212. may pass in a dictionary of type conversion information to ``parse()`` and
  213. ``compile()``.
  214. The converter will be passed the field string matched. Whatever it returns
  215. will be substituted in the ``Result`` instance for that field.
  216. Your custom type conversions may override the builtin types if you supply one
  217. with the same identifier.
  218. >>> def shouty(string):
  219. ... return string.upper()
  220. ...
  221. >>> parse('{:shouty} world', 'hello world', dict(shouty=shouty))
  222. <Result ('HELLO',) {}>
  223. If the type converter has the optional ``pattern`` attribute, it is used as
  224. regular expression for better pattern matching (instead of the default one).
  225. >>> def parse_number(text):
  226. ... return int(text)
  227. >>> parse_number.pattern = r'\d+'
  228. >>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
  229. <Result () {'number': 42}>
  230. >>> _ = parse('Answer: {:Number}', 'Answer: Alice', dict(Number=parse_number))
  231. >>> assert _ is None, "MISMATCH"
  232. You can also use the ``with_pattern(pattern)`` decorator to add this
  233. information to a type converter function:
  234. >>> from parse import with_pattern
  235. >>> @with_pattern(r'\d+')
  236. ... def parse_number(text):
  237. ... return int(text)
  238. >>> parse('Answer: {number:Number}', 'Answer: 42', dict(Number=parse_number))
  239. <Result () {'number': 42}>
  240. A more complete example of a custom type might be:
  241. >>> yesno_mapping = {
  242. ... "yes": True, "no": False,
  243. ... "on": True, "off": False,
  244. ... "true": True, "false": False,
  245. ... }
  246. >>> @with_pattern(r"|".join(yesno_mapping))
  247. ... def parse_yesno(text):
  248. ... return yesno_mapping[text.lower()]
  249. If the type converter ``pattern`` uses regex-grouping (with parenthesis),
  250. you should indicate this by using the optional ``regex_group_count`` parameter
  251. in the ``with_pattern()`` decorator:
  252. >>> @with_pattern(r'((\d+))', regex_group_count=2)
  253. ... def parse_number2(text):
  254. ... return int(text)
  255. >>> parse('Answer: {:Number2} {:Number2}', 'Answer: 42 43', dict(Number2=parse_number2))
  256. <Result (42, 43) {}>
  257. Otherwise, this may cause parsing problems with unnamed/fixed parameters.
  258. Potential Gotchas
  259. -----------------
  260. `parse()` will always match the shortest text necessary (from left to right)
  261. to fulfil the parse pattern, so for example:
  262. >>> pattern = '{dir1}/{dir2}'
  263. >>> data = 'root/parent/subdir'
  264. >>> sorted(parse(pattern, data).named.items())
  265. [('dir1', 'root'), ('dir2', 'parent/subdir')]
  266. So, even though `{'dir1': 'root/parent', 'dir2': 'subdir'}` would also fit
  267. the pattern, the actual match represents the shortest successful match for
  268. `dir1`.
  269. ----
  270. **Version history (in brief)**:
  271. - 1.12.0 Do not assume closing brace when an opening one is found (thanks @mattsep)
  272. - 1.11.1 Revert having unicode char in docstring, it breaks Bamboo builds(?!)
  273. - 1.11.0 Implement `__contains__` for Result instances.
  274. - 1.10.0 Introduce a "letters" matcher, since "w" matches numbers
  275. also.
  276. - 1.9.1 Fix deprecation warnings around backslashes in regex strings
  277. (thanks Mickael Schoentgen). Also fix some documentation formatting
  278. issues.
  279. - 1.9.0 We now honor precision and width specifiers when parsing numbers
  280. and strings, allowing parsing of concatenated elements of fixed width
  281. (thanks Julia Signell)
  282. - 1.8.4 Add LICENSE file at request of packagers.
  283. Correct handling of AM/PM to follow most common interpretation.
  284. Correct parsing of hexadecimal that looks like a binary prefix.
  285. Add ability to parse case sensitively.
  286. Add parsing of numbers to Decimal with "F" (thanks John Vandenberg)
  287. - 1.8.3 Add regex_group_count to with_pattern() decorator to support
  288. user-defined types that contain brackets/parenthesis (thanks Jens Engel)
  289. - 1.8.2 add documentation for including braces in format string
  290. - 1.8.1 ensure bare hexadecimal digits are not matched
  291. - 1.8.0 support manual control over result evaluation (thanks Timo Furrer)
  292. - 1.7.0 parse dict fields (thanks Mark Visser) and adapted to allow
  293. more than 100 re groups in Python 3.5+ (thanks David King)
  294. - 1.6.6 parse Linux system log dates (thanks Alex Cowan)
  295. - 1.6.5 handle precision in float format (thanks Levi Kilcher)
  296. - 1.6.4 handle pipe "|" characters in parse string (thanks Martijn Pieters)
  297. - 1.6.3 handle repeated instances of named fields, fix bug in PM time
  298. overflow
  299. - 1.6.2 fix logging to use local, not root logger (thanks Necku)
  300. - 1.6.1 be more flexible regarding matched ISO datetimes and timezones in
  301. general, fix bug in timezones without ":" and improve docs
  302. - 1.6.0 add support for optional ``pattern`` attribute in user-defined types
  303. (thanks Jens Engel)
  304. - 1.5.3 fix handling of question marks
  305. - 1.5.2 fix type conversion error with dotted names (thanks Sebastian Thiel)
  306. - 1.5.1 implement handling of named datetime fields
  307. - 1.5 add handling of dotted field names (thanks Sebastian Thiel)
  308. - 1.4.1 fix parsing of "0" in int conversion (thanks James Rowe)
  309. - 1.4 add __getitem__ convenience access on Result.
  310. - 1.3.3 fix Python 2.5 setup.py issue.
  311. - 1.3.2 fix Python 3.2 setup.py issue.
  312. - 1.3.1 fix a couple of Python 3.2 compatibility issues.
  313. - 1.3 added search() and findall(); removed compile() from ``import *``
  314. export as it overwrites builtin.
  315. - 1.2 added ability for custom and override type conversions to be
  316. provided; some cleanup
  317. - 1.1.9 to keep things simpler number sign is handled automatically;
  318. significant robustification in the face of edge-case input.
  319. - 1.1.8 allow "d" fields to have number base "0x" etc. prefixes;
  320. fix up some field type interactions after stress-testing the parser;
  321. implement "%" type.
  322. - 1.1.7 Python 3 compatibility tweaks (2.5 to 2.7 and 3.2 are supported).
  323. - 1.1.6 add "e" and "g" field types; removed redundant "h" and "X";
  324. removed need for explicit "#".
  325. - 1.1.5 accept textual dates in more places; Result now holds match span
  326. positions.
  327. - 1.1.4 fixes to some int type conversion; implemented "=" alignment; added
  328. date/time parsing with a variety of formats handled.
  329. - 1.1.3 type conversion is automatic based on specified field types. Also added
  330. "f" and "n" types.
  331. - 1.1.2 refactored, added compile() and limited ``from parse import *``
  332. - 1.1.1 documentation improvements
  333. - 1.1.0 implemented more of the `Format Specification Mini-Language`_
  334. and removed the restriction on mixing fixed-position and named fields
  335. - 1.0.0 initial release
  336. This code is copyright 2012-2019 Richard Jones <richard@python.org>
  337. See the end of the source file for the license of use.