1 | ---
|
2 | title: YSH Expression Language (Oils Reference)
|
3 | all_docs_url: ..
|
4 | body_css_class: width40
|
5 | default_highlighter: oils-sh
|
6 | preserve_anchor_case: yes
|
7 | ---
|
8 |
|
9 | <div class="doc-ref-header">
|
10 |
|
11 | [Oils Reference](index.html) —
|
12 | Chapter **YSH Expression Language**
|
13 |
|
14 | </div>
|
15 |
|
16 | This chapter describes the YSH expression language, which includes [Egg
|
17 | Expressions]($xref:eggex).
|
18 |
|
19 | <div id="dense-toc">
|
20 | </div>
|
21 |
|
22 | ## Assignment
|
23 |
|
24 | ### assign
|
25 |
|
26 | The `=` operator is used with assignment keywords:
|
27 |
|
28 | var x = 42
|
29 | setvar x = 43
|
30 |
|
31 | const y = 'k'
|
32 |
|
33 | setglobal z = 'g'
|
34 |
|
35 | ### aug-assign
|
36 |
|
37 | The augmented assignment operators are:
|
38 |
|
39 | += -= *= /= **= //= %=
|
40 | &= |= ^= <<= >>=
|
41 |
|
42 | They are used with `setvar` and `setglobal`. For example:
|
43 |
|
44 | setvar x += 2
|
45 |
|
46 | is the same as:
|
47 |
|
48 | setvar x = x + 2
|
49 |
|
50 | Likewise, these are the same:
|
51 |
|
52 | setglobal a[i] -= 1
|
53 |
|
54 | setglobal a[i] = a[i] - 1
|
55 |
|
56 | ## Literals
|
57 |
|
58 | ### atom-literal
|
59 |
|
60 | YSH uses JavaScript-like spellings for these three "atoms":
|
61 |
|
62 | null # type Null
|
63 | true false # type Bool
|
64 |
|
65 | Note: to signify "no value", you may sometimes use an empty string `''`,
|
66 | instead of `null`.
|
67 |
|
68 | ### int-literal
|
69 |
|
70 | Examples of integer literals:
|
71 |
|
72 | var decimal = 42
|
73 | var big = 42_000
|
74 |
|
75 | var hex = 0x0010_ffff
|
76 |
|
77 | var octal = 0o755
|
78 |
|
79 | var binary = 0b0001_0000
|
80 |
|
81 | ### float-lit
|
82 |
|
83 | Examples of float literals:
|
84 |
|
85 | var myfloat = 3.14
|
86 |
|
87 | var f2 = -1.5e-100
|
88 |
|
89 | ### char-literal
|
90 |
|
91 | Three kinds of unquoted backslash escapes are allowed in expression mode. They
|
92 | match what's available in quoted J8-style strings:
|
93 |
|
94 | var backslash = \\
|
95 | var quotes = \' ++ \" # same as u'\'' ++ '"'
|
96 |
|
97 | var mu = \u{3bc} # same as u'\u{3bc}'
|
98 |
|
99 | var nul = \y00 # same as b'\y00'
|
100 |
|
101 | ### ysh-string
|
102 |
|
103 | YSH has single and double-quoted strings borrowed from Bourne shell, and
|
104 | C-style strings borrowed from J8 Notation.
|
105 |
|
106 | Double quoted strings respect `$` interpolation:
|
107 |
|
108 | var dq = "hello $world and $(hostname)"
|
109 |
|
110 | You can add a `$` before the left quote to be explicit: `$"x is $x"` rather
|
111 | than `"x is $x"`.
|
112 |
|
113 | Single quoted strings may be raw:
|
114 |
|
115 | var s = r'line\n' # raw string means \n is literal, NOT a newline
|
116 |
|
117 | Or *J8 strings* with backslash escapes:
|
118 |
|
119 | var s = u'line\n \u{3bc}' # unicode string means \n is a newline
|
120 | var s = b'line\n \u{3bc} \yff' # same thing, but also allows bytes
|
121 |
|
122 | Both `u''` and `b''` strings evaluate to the single `Str` type. The difference
|
123 | is that `b''` strings allow the `\yff` byte escape.
|
124 |
|
125 | #### Notes
|
126 |
|
127 | There's no way to express a single quote in raw strings. Use one of the other
|
128 | forms instead:
|
129 |
|
130 | var sq = "single quote: ' "
|
131 | var sq = u'single quote: \' '
|
132 |
|
133 | Sometimes you can omit the `r`, e.g. where there are no backslashes and thus no
|
134 | ambiguity:
|
135 |
|
136 | echo 'foo'
|
137 | echo r'foo' # same thing
|
138 |
|
139 | The `u''` and `b''` strings are called *J8 strings* because the syntax in YSH
|
140 | **code** matches JSON-like **data**.
|
141 |
|
142 | var strU = u'mu = \u{3bc}' # J8 string with escapes
|
143 | var strB = b'bytes \yff' # J8 string that can express byte strings
|
144 |
|
145 | More examples:
|
146 |
|
147 | var myRaw = r'[a-z]\n' # raw strings can be used for regexes (not
|
148 | # eggexes)
|
149 |
|
150 | ### triple-quoted
|
151 |
|
152 | Triple-quoted string literals have leading whitespace stripped on each line.
|
153 | They come in the same variants:
|
154 |
|
155 | var dq = """
|
156 | hello $world and $(hostname)
|
157 | no leading whitespace
|
158 | """
|
159 |
|
160 | var myRaw = r'''
|
161 | raw string
|
162 | no leading whitespace
|
163 | '''
|
164 |
|
165 | var strU = u'''
|
166 | string that happens to be unicode \u{3bc}
|
167 | no leading whitespace
|
168 | '''
|
169 |
|
170 | var strB = b'''
|
171 | string that happens to be bytes \u{3bc} \yff
|
172 | no leading whitespace
|
173 | '''
|
174 |
|
175 | Again, you can omit the `r` prefix if there's no backslash, because it's not
|
176 | ambiguous:
|
177 |
|
178 | var myRaw = '''
|
179 | raw string
|
180 | no leading whitespace
|
181 | '''
|
182 |
|
183 | ### str-template
|
184 |
|
185 | String templates use the same syntax as double-quoted strings:
|
186 |
|
187 | var mytemplate = ^"name = $name, age = $age"
|
188 |
|
189 | Related topics:
|
190 |
|
191 | - [Str => replace](chap-type-method.html#replace)
|
192 | - [ysh-string](chap-expr-lang.html#ysh-string)
|
193 |
|
194 | ### list-literal
|
195 |
|
196 | Lists have a Python-like syntax:
|
197 |
|
198 | var mylist = ['one', 'two', [42, 43]]
|
199 |
|
200 | And a shell-like syntax:
|
201 |
|
202 | var list2 = :| one two |
|
203 |
|
204 | The shell-like syntax accepts the same syntax as a simple command:
|
205 |
|
206 | ls $mystr @ARGV *.py {foo,bar}@example.com
|
207 |
|
208 | # Rather than executing ls, evaluate words into a List
|
209 | var cmd = :| ls $mystr @ARGV *.py {foo,bar}@example.com |
|
210 |
|
211 | ### dict-literal
|
212 |
|
213 | Dicts look like JavaScript.
|
214 |
|
215 | var d = {
|
216 | key1: 'value', # key can be unquoted if it looks like a var name
|
217 | 'key2': 42, # or quote it
|
218 |
|
219 | ['key2' ++ suffix]: 43, # bracketed expression
|
220 | }
|
221 |
|
222 | Omitting a value means that the corresponding key takes the value of a var of
|
223 | the same name:
|
224 |
|
225 | ysh$ var x = 42
|
226 | ysh$ var y = 43
|
227 |
|
228 | ysh$ var d = {x, y} # values omitted
|
229 | ysh$ = d
|
230 | (Dict) {x: 42, y: 43}
|
231 |
|
232 | ### range
|
233 |
|
234 | A range is a sequence of numbers that can be iterated over:
|
235 |
|
236 | for i in (0 ..< 3) {
|
237 | echo $i
|
238 | }
|
239 | => 0
|
240 | => 1
|
241 | => 2
|
242 |
|
243 | The `..<` syntax is for open ranges. `..=` can be used for closed ranges:
|
244 |
|
245 | for i in (0 ..= 3) {
|
246 | echo $i
|
247 | }
|
248 | => 0
|
249 | => 1
|
250 | => 2
|
251 | => 3
|
252 |
|
253 | ### block-expr
|
254 |
|
255 | In YSH expressions, we use `^()` to create a [Command][] object:
|
256 |
|
257 | var myblock = ^(echo $PWD; ls *.txt)
|
258 |
|
259 | It's more common for [Command][] objects to be created with block arguments,
|
260 | which are not expressions:
|
261 |
|
262 | cd /tmp {
|
263 | echo $PWD
|
264 | ls *.txt
|
265 | }
|
266 |
|
267 | [Command]: chap-type-method.html#Command
|
268 |
|
269 | ### expr-literal
|
270 |
|
271 | An expression literal is an object that holds an unevaluated expression:
|
272 |
|
273 | var myexpr = ^[1 + 2*3]
|
274 |
|
275 | [Expr]: chap-type-method.html#Expr
|
276 |
|
277 | ## Operators
|
278 |
|
279 | ### op-precedence
|
280 |
|
281 | YSH operator precedence is identical to Python's operator precedence.
|
282 |
|
283 | New operators:
|
284 |
|
285 | - `++` has the same precedence as `+`
|
286 | - `->` and `=>` have the same precedence as `.`
|
287 |
|
288 | <!-- TODO: show grammar -->
|
289 |
|
290 |
|
291 | <h3 id="concat">concat <code>++</code></h3>
|
292 |
|
293 | The concatenation operator works on `Str` objects:
|
294 |
|
295 | ysh$ var s = 'hello'
|
296 | ysh$ var t = s ++ ' world'
|
297 |
|
298 | ysh$ = t
|
299 | (Str) "hello world"
|
300 |
|
301 | and `List` objects:
|
302 |
|
303 | ysh$ var L = ['one', 'two']
|
304 | ysh$ var M = L ++ ['three', '4']
|
305 |
|
306 | ysh$ = M
|
307 | (List) ["one", "two", "three", "4"]
|
308 |
|
309 | String interpolation can be nicer than `++`:
|
310 |
|
311 | var t2 = "${s} world" # same as t
|
312 |
|
313 | Likewise, splicing lists can be nicer:
|
314 |
|
315 | var M2 = :| @L three 4 | # same as M
|
316 |
|
317 | ### ysh-equals
|
318 |
|
319 | YSH has strict equality:
|
320 |
|
321 | a === b # Python-like, without type conversion
|
322 | a !== b # negated
|
323 |
|
324 | And type converting equality:
|
325 |
|
326 | '3' ~== 3 # True, type conversion
|
327 |
|
328 | The `~==` operator expects a string as the left operand.
|
329 |
|
330 | ---
|
331 |
|
332 | Note that:
|
333 |
|
334 | - `3 === 3.0` is false because integers and floats are different types, and
|
335 | there is no type conversion.
|
336 | - `3 ~== 3.0` is an error, because the left operand isn't a string.
|
337 |
|
338 | You may want to use explicit `int()` and `float()` to convert numbers, and then
|
339 | compare them.
|
340 |
|
341 | ---
|
342 |
|
343 | Compare objects for identity with `is`:
|
344 |
|
345 | ysh$ var d = {}
|
346 | ysh$ var e = d
|
347 |
|
348 | ysh$ = d is d
|
349 | (Bool) true
|
350 |
|
351 | ysh$ = d is {other: 'dict'}
|
352 | (Bool) false
|
353 |
|
354 | To negate `is`, use `is not` (like Python:
|
355 |
|
356 | ysh$ d is not {other: 'dict'}
|
357 | (Bool) true
|
358 |
|
359 | ### ysh-in
|
360 |
|
361 | The `in` operator tests if a key is in a dictionary:
|
362 |
|
363 | var d = {k: 42}
|
364 | if ('k' in d) {
|
365 | echo yes
|
366 | } # => yes
|
367 |
|
368 | Unlike Python, `in` doesn't work on `Str` and `List` instances. This because
|
369 | those operations take linear time rather than constant time (O(n) rather than
|
370 | O(1)).
|
371 |
|
372 | TODO: Use `includes() / contains()` methods instead.
|
373 |
|
374 | ### ysh-compare
|
375 |
|
376 | The comparison operators apply to integers or floats:
|
377 |
|
378 | 4 < 4 # => false
|
379 | 4 <= 4 # => true
|
380 |
|
381 | 5.0 > 5.0 # => false
|
382 | 5.0 >= 5.0 # => true
|
383 |
|
384 | Example in context:
|
385 |
|
386 | if (x < 0) {
|
387 | echo 'x is negative'
|
388 | }
|
389 |
|
390 | ### ysh-logical
|
391 |
|
392 | The logical operators take boolean operands, and are spelled like Python:
|
393 |
|
394 | not
|
395 | and or
|
396 |
|
397 | Note that they are distinct from `! && ||`, which are part of the [command
|
398 | language](chap-cmd-lang.html).
|
399 |
|
400 | ### ysh-arith
|
401 |
|
402 | YSH supports most of the arithmetic operators from Python. Notably, `/` and `%`
|
403 | differ from Python as [they round toward zero, not negative
|
404 | infinity](https://www.oilshell.org/blog/2024/03/release-0.21.0.html#integers-dont-do-whatever-python-or-c-does).
|
405 |
|
406 | Use `+ - *` for `Int` or `Float` addition, subtraction and multiplication. If
|
407 | any of the operands are `Float`s, then the output will also be a `Float`.
|
408 |
|
409 | Use `/` and `//` for `Float` division and `Int` division, respectively. `/`
|
410 | will _always_ result in a `Float`, meanwhile `//` will _always_ result in an
|
411 | `Int`.
|
412 |
|
413 | = 1 / 2 # => (Float) 0.5
|
414 | = 1 // 2 # => (Int) 0
|
415 |
|
416 | Use `%` to compute the _remainder_ of integer division. The left operand must
|
417 | be an `Int` and the right a _positive_ `Int`.
|
418 |
|
419 | = 1 % 2 # -> (Int) 1
|
420 | = -4 % 2 # -> (Int) 0
|
421 |
|
422 | Use `**` for exponentiation. The left operand must be an `Int` and the right a
|
423 | _positive_ `Int`.
|
424 |
|
425 | All arithmetic operators may coerce either of their operands from strings to a
|
426 | number, provided those strings are formatted as numbers.
|
427 |
|
428 | = 10 + '1' # => (Int) 11
|
429 |
|
430 | Operators like `+ - * /` will coerce strings to _either_ an `Int` or `Float`.
|
431 | However, operators like `// ** %` and bit shifts will coerce strings _only_ to
|
432 | an `Int`.
|
433 |
|
434 | = '1.14' + '2' # => (Float) 3.14
|
435 | = '1.14' % '2' # Type Error: Left operand is a Str
|
436 |
|
437 | ### ysh-bitwise
|
438 |
|
439 | Bitwise operators are like Python and C:
|
440 |
|
441 | ~ # unary complement
|
442 |
|
443 | & | ^ # binary and, or, xor
|
444 |
|
445 | >> << # bit shift
|
446 |
|
447 | ### ysh-ternary
|
448 |
|
449 | The ternary operator is borrowed from Python:
|
450 |
|
451 | display = 'yes' if len(s) else 'empty'
|
452 |
|
453 | ### ysh-index
|
454 |
|
455 | `Str` objects can be indexed by byte:
|
456 |
|
457 | ysh$ var s = 'cat'
|
458 | ysh$ = mystr[1]
|
459 | (Str) 'a'
|
460 |
|
461 | ysh$ = mystr[-1] # index from the end
|
462 | (Str) 't'
|
463 |
|
464 | `List` objects:
|
465 |
|
466 | ysh$ var mylist = [1, 2, 3]
|
467 | ysh$ = mylist[2]
|
468 | (Int) 3
|
469 |
|
470 | `Dict` objects are indexed by string key:
|
471 |
|
472 | ysh$ var mydict = {'key': 42}
|
473 | ysh$ = mydict['key']
|
474 | (Int) 42
|
475 |
|
476 | ### ysh-attr
|
477 |
|
478 | The `.` operator looks up values on either `Dict` or `Obj` instances.
|
479 |
|
480 | On dicts, it looks for the value associated with a key. That is, the
|
481 | expression `mydict.key` is short for `mydict['key']` (like JavaScript, but
|
482 | unlike Python.)
|
483 |
|
484 | ---
|
485 |
|
486 | On objects, the expression `obj.x` looks for attributes, with a special rule
|
487 | for bound methods. The rules are:
|
488 |
|
489 | 1. Search the properties of `obj` for a field named `x`.
|
490 | - If it exists, return the value literally. (It can be of any type: `Func`, `Int`,
|
491 | `Str`, ...)
|
492 | 2. Search up the prototype chain for a field named `x`.
|
493 | - If it exists, and is **not** a `Func`, return the value literally.
|
494 | - If it **is** a `Func`, return **bound method**, which is an (object,
|
495 | function) pair.
|
496 |
|
497 | Later, when the bound method is called, the object is passed as the first
|
498 | argument to the function (`self`), making it a method call. This is how a
|
499 | method has access to the object's properties.
|
500 |
|
501 | Example of first rule:
|
502 |
|
503 | func Free(i) {
|
504 | return (i + 1)
|
505 | }
|
506 | var module = Object(null, {Free})
|
507 | echo $[module.Free(42)] # => 43
|
508 |
|
509 | Example of second rule:
|
510 |
|
511 | func method(self, i) {
|
512 | return (self.n + i)
|
513 | }
|
514 | var methods = Object(null, {method})
|
515 | var obj = Object(methods, {n: 10})
|
516 | echo $[obj.method(42)] # => 52
|
517 |
|
518 | ### ysh-slice
|
519 |
|
520 | Slicing gives you a subsequence of a `Str` or `List`, as in Python.
|
521 |
|
522 | Negative indices are relative to the end.
|
523 |
|
524 | String example:
|
525 |
|
526 | $ var s = 'spam eggs'
|
527 | $ pp (s[1:-1])
|
528 | (Str) "pam egg"
|
529 |
|
530 | $ echo "x $[s[2:]]"
|
531 | x am eggs
|
532 |
|
533 | List example:
|
534 |
|
535 | $ var foods = ['ale', 'bean', 'corn']
|
536 | $ pp (foods[-2:])
|
537 | (List) ["bean","corn"]
|
538 |
|
539 | $ write -- @[foods[:2]]
|
540 | ale
|
541 | bean
|
542 |
|
543 | ### func-call
|
544 |
|
545 | A function call expression looks like Python:
|
546 |
|
547 | ysh$ = f('s', 't', named=42)
|
548 |
|
549 | A semicolon `;` can be used after positional args and before named args, but
|
550 | isn't always required:
|
551 |
|
552 | ysh$ = f('s', 't'; named=42)
|
553 |
|
554 | In these cases, the `;` is necessary:
|
555 |
|
556 | ysh$ = f(...args; ...kwargs)
|
557 |
|
558 | ysh$ = f(42, 43; ...kwargs)
|
559 |
|
560 | ### thin-arrow
|
561 |
|
562 | The thin arrow is for mutating methods:
|
563 |
|
564 | var mylist = ['bar']
|
565 | call mylist->pop()
|
566 |
|
567 | var mydict = {name: 'foo'}
|
568 | call mydict->erase('name')
|
569 |
|
570 | On `Obj` instances, `obj->mymethod` looks up the prototype chain for a function
|
571 | named `M/mymethod`. The `M/` prefix signals mutation.
|
572 |
|
573 | Example:
|
574 |
|
575 | func inc(self, n) {
|
576 | setvar self.i += n
|
577 | }
|
578 | var Counter_methods = Object(null, {'M/inc': inc})
|
579 | var c = Object(Counter_methods, {i: 0})
|
580 |
|
581 | call c->inc(5)
|
582 | echo $[c.i] # => 5
|
583 |
|
584 | It does **not** look in the properties of an object.
|
585 |
|
586 | ### fat-arrow
|
587 |
|
588 | The fat arrow is for transforming methods:
|
589 |
|
590 | if (s => startsWith('prefix')) {
|
591 | echo 'yes'
|
592 | }
|
593 |
|
594 | If the method lookup on `s` fails, it looks for free functions. This means it
|
595 | can be used for "chaining" transformations:
|
596 |
|
597 | var x = myFunc() => list() => join()
|
598 |
|
599 | ### match-ops
|
600 |
|
601 | YSH has four pattern matching operators: `~ !~ ~~ !~~`.
|
602 |
|
603 | Does string match an **eggex**?
|
604 |
|
605 | var filename = 'x42.py'
|
606 | if (filename ~ / d+ /) {
|
607 | echo 'number'
|
608 | }
|
609 |
|
610 | Does a string match a POSIX regular expression (ERE syntax)?
|
611 |
|
612 | if (filename ~ '[[:digit:]]+') {
|
613 | echo 'number'
|
614 | }
|
615 |
|
616 | Negate the result with the `!~` operator:
|
617 |
|
618 | if (filename !~ /space/ ) {
|
619 | echo 'no space'
|
620 | }
|
621 |
|
622 | if (filename !~ '[[:space:]]' ) {
|
623 | echo 'no space'
|
624 | }
|
625 |
|
626 | Does a string match a **glob**?
|
627 |
|
628 | if (filename ~~ '*.py') {
|
629 | echo 'Python'
|
630 | }
|
631 |
|
632 | if (filename !~~ '*.py') {
|
633 | echo 'not Python'
|
634 | }
|
635 |
|
636 | Take care not to confuse glob patterns and regular expressions.
|
637 |
|
638 | - Related doc: [YSH Regex API](../ysh-regex-api.html)
|
639 |
|
640 | ## Eggex
|
641 |
|
642 | ### re-literal
|
643 |
|
644 | An eggex literal looks like this:
|
645 |
|
646 | / expression ; flags ; translation preference /
|
647 |
|
648 | The flags and translation preference are both optional.
|
649 |
|
650 | Examples:
|
651 |
|
652 | var pat = / d+ / # => [[:digit:]]+
|
653 |
|
654 | You can specify flags passed to libc `regcomp()`:
|
655 |
|
656 | var pat = / d+ ; reg_icase reg_newline /
|
657 |
|
658 | You can specify a translation preference after a second semi-colon:
|
659 |
|
660 | var pat = / d+ ; ; ERE /
|
661 |
|
662 | Right now the translation preference does nothing. It could be used to
|
663 | translate eggex to PCRE or Python syntax.
|
664 |
|
665 | - Related doc: [Egg Expressions](../eggex.html)
|
666 |
|
667 | ### re-primitive
|
668 |
|
669 | There are two kinds of eggex primitives.
|
670 |
|
671 | "Zero-width assertions" match a position rather than a character:
|
672 |
|
673 | %start # translates to ^
|
674 | %end # translates to $
|
675 |
|
676 | Literal characters appear within **single** quotes:
|
677 |
|
678 | 'oh *really*' # translates to regex-escaped string
|
679 |
|
680 | Double-quoted strings are **not** eggex primitives. Instead, you can use
|
681 | splicing of strings:
|
682 |
|
683 | var dq = "hi $name"
|
684 | var eggex = / @dq /
|
685 |
|
686 | ### class-literal
|
687 |
|
688 | An eggex character class literal specifies a set. It can have individual
|
689 | characters and ranges:
|
690 |
|
691 | [ 'x' 'y' 'z' a-f A-F 0-9 ] # 3 chars, 3 ranges
|
692 |
|
693 | Omit quotes on ASCII characters:
|
694 |
|
695 | [ x y z ] # avoid typing 'x' 'y' 'z'
|
696 |
|
697 | Sets of characters can be written as strings
|
698 |
|
699 | [ 'xyz' ] # any of 3 chars, not a sequence of 3 chars
|
700 |
|
701 | Backslash escapes are respected:
|
702 |
|
703 | [ \\ \' \" \0 ]
|
704 | [ \xFF \u{3bc} ]
|
705 |
|
706 | (Note that we don't use `\yFF`, as in J8 strings.)
|
707 |
|
708 | Splicing:
|
709 |
|
710 | [ @str_var ]
|
711 |
|
712 | Negation always uses `!`
|
713 |
|
714 | ![ a-f A-F 'xyz' @str_var ]
|
715 |
|
716 | ### named-class
|
717 |
|
718 | Perl-like shortcuts for sets of characters:
|
719 |
|
720 | [ dot ] # => .
|
721 | [ digit ] # => [[:digit:]]
|
722 | [ space ] # => [[:space:]]
|
723 | [ word ] # => [[:alpha:]][[:digit:]]_
|
724 |
|
725 | Abbreviations:
|
726 |
|
727 | [ d s w ] # Same as [ digit space word ]
|
728 |
|
729 | Valid POSIX classes:
|
730 |
|
731 | alnum cntrl lower space
|
732 | alpha digit print upper
|
733 | blank graph punct xdigit
|
734 |
|
735 | Negated:
|
736 |
|
737 | !digit !space !word
|
738 | !d !s !w
|
739 | !alnum # etc.
|
740 |
|
741 | ### re-repeat
|
742 |
|
743 | Eggex repetition looks like POSIX syntax:
|
744 |
|
745 | / 'a'? / # zero or one
|
746 | / 'a'* / # zero or more
|
747 | / 'a'+ / # one or more
|
748 |
|
749 | Counted repetitions:
|
750 |
|
751 | / 'a'{3} / # exactly 3 repetitions
|
752 | / 'a'{2,4} / # between 2 to 4 repetitions
|
753 |
|
754 | ### re-compound
|
755 |
|
756 | Sequence expressions with a space:
|
757 |
|
758 | / word digit digit / # Matches 3 characters in sequence
|
759 | # Examples: a42, b51
|
760 |
|
761 | (Compare `/ [ word digit ] /`, which is a set matching 1 character.)
|
762 |
|
763 | Alternation with `|`:
|
764 |
|
765 | / word | digit / # Matches 'a' OR '9', for example
|
766 |
|
767 | Grouping with parentheses:
|
768 |
|
769 | / (word digit) | \\ / # Matches a9 or \
|
770 |
|
771 | ### re-capture
|
772 |
|
773 | To retrieve a substring of a string that matches an Eggex, use a "capture
|
774 | group" like `<capture ...>`.
|
775 |
|
776 | Here's an eggex with a **positional** capture:
|
777 |
|
778 | var pat = / 'hi ' <capture d+> / # access with _group(1)
|
779 | # or Match => _group(1)
|
780 |
|
781 | Captures can be **named**:
|
782 |
|
783 | <capture d+ as month> # access with _group('month')
|
784 | # or Match => group('month')
|
785 |
|
786 | Captures can also have a type **conversion func**:
|
787 |
|
788 | <capture d+ : int> # _group(1) returns Int
|
789 |
|
790 | <capture d+ as month: int> # _group('month') returns Int
|
791 |
|
792 | Related docs and help topics:
|
793 |
|
794 | - [YSH Regex API](../ysh-regex-api.html)
|
795 | - [`_group()`](chap-builtin-func.html#_group)
|
796 | - [`Match => group()`](chap-type-method.html#group)
|
797 |
|
798 | ### re-splice
|
799 |
|
800 | To build an eggex out of smaller expressions, you can **splice** eggexes
|
801 | together:
|
802 |
|
803 | var D = / [0-9][0-9] /
|
804 | var time = / @D ':' @D / # [0-9][0-9]:[0-9][0-9]
|
805 |
|
806 | If the variable begins with a capital letter, you can omit `@`:
|
807 |
|
808 | var ip = / D ':' D /
|
809 |
|
810 | You can also splice a string:
|
811 |
|
812 | var greeting = 'hi'
|
813 | var pat = / @greeting ' world' / # hi world
|
814 |
|
815 | Splicing is **not** string concatenation; it works on eggex subtrees.
|
816 |
|
817 | ### re-flags
|
818 |
|
819 | Valid ERE flags, which are passed to libc's `regcomp()`:
|
820 |
|
821 | - `reg_icase` aka `i` - ignore case
|
822 | - `reg_newline` - 4 matching changes related to newlines
|
823 |
|
824 | See `man regcomp`.
|
825 |
|
826 | ### re-multiline
|
827 |
|
828 | Multi-line eggexes aren't yet implemented. Splicing makes it less necessary:
|
829 |
|
830 | var Name = / <capture [a-z]+ as name> /
|
831 | var Num = / <capture d+ as num> /
|
832 | var Space = / <capture s+ as space> /
|
833 |
|
834 | # For variables named like CapWords, splicing @Name doesn't require @
|
835 | var lexer = / Name | Num | Space /
|