Matcher AppendReplacement Token Swap
Expand template tokens with appendReplacement and appendTail: replacements are appended into a StringBuilder while group references stay intact.
Page 25 of 50
Expand template tokens with appendReplacement and appendTail: replacements are appended into a StringBuilder while group references stay intact.
Pick the right Matcher entry point: matches demands the whole input, lookingAt anchors the prefix, find scans anywhere for the next hit.
Constrain regex scanning to a slice of a large payload with Matcher.region, so hits outside [regionStart, regionEnd) are never reported.
Stream regex matches as MatchResult objects with Matcher.results, feeding the pipeline directly instead of collecting into a list first.
Stamp API payloads with fixed-offset OffsetDateTime and parse ISO-8601 back, comparing instants instead of strings across offsets.
Handle both branches of an Optional in one call with ifPresentOrElse: the value action and the empty action live side by side, no if-get wrapping.
Build lazy fallbacks with Optional.or: each supplier runs only when the previous chain stage is empty, unlike eager orElse arguments.
Build a tiny lexer with PushbackReader: read one char, classify it, and unread it when the next loop must decide all over again.
Deconstruct records directly in case labels and nest patterns so extraction and validation happen in one exhausted switch.
Discover implementations declared in META-INF/services through java.util.ServiceLoader, iterating lazily instead of hand-wired class name lists.
Flatten each element to zero or more outputs with Stream mapMulti, avoiding the per-element stream allocation that flatMap pays for.
Split structured strings with the two-arg split limit: -1 preserves trailing empty fields that the default split silently drops.
Turn escape sequences that exist as characters into their real control characters with translateEscapes, without regex or manual replacement.
Create platform threads through Thread.ofPlatform with explicit names and an uncaught handler instead of leaving unnamed Thread-N workers behind.
Detect a real monitor deadlock at runtime with findDeadlockedThreads, then report each victim together with the thread holding its lock.
Mirror a folder with Files.walkFileTree: preVisitDirectory creates destinations, visitFile copies files, and visitFileFailed skips unreadable entries.
Store metadata beside objects with WeakHashMap: entries vanish once keys are garbage collected, so caches do not leak strong references.
Map compares object keys by reference, so multi-field lookups need one keyOf helper turning tenant, user, and day into a stable string key.
Tally labeled calls with console.count, nest logs with group and groupEnd, measure spans with time and timeEnd, and assert only prints on failure.
crypto.randomUUID produces RFC 4122 v4 identifiers with 122 random bits, version and variant nibbles fixed by the spec at known positions.
Check the clock before each item, stop the moment a time budget runs out, and hand the untouched tail to the next tick instead of timing out mid-item.
Without a comparator, sort stringifies elements and orders them by code units, so 10 lands before 2; numeric arrays need a subtraction comparator.
Assemble rows on a detached fragment and attach once, so the document sees a single insertion; the fragment itself never enters the tree.
Keep Tab cycling inside a container by listening for keydown and focusing the next or previous focusable, wrapping at both ends.
getMonth returns 0-11 and getDay puts Sunday at 0, so labels need lookup tables and month 12 in the constructor rolls into the next year.
Drop marks around work and read the spans back with measure; entries stay buffered for later inspection instead of ad hoc timing prints.
Object.keys and JSON.stringify skip symbol keys, so cloning or auditing whole records needs Reflect.ownKeys, the only builtin that lists every own key.
Dollar sequences like $1, $&, and $<name> expand inside replacement strings; function replacements return literal text with no expansion at all.
Read the high-resolution timestamp in each frame callback, clamp long gaps after background tabs, and stop the loop on a frame budget.
Integers beyond 2^53 lose exactness, so Number.isSafeInteger guards both inputs and results before IDs or amounts enter arithmetic.
Steps that consume the previous result must await in order, while unrelated calls belong in the same Promise.all so they run alongside the chain.
The [object X] label from Object.prototype.toString reads Symbol.toStringTag, so custom classes can brand their diagnostics without touching instanceof.
Compile route templates once and exec or test requests against them, extracting named groups and rejecting wrong hosts without hand-parsing.
AbortSignal.timeout builds a deadline signal that aborts itself with a TimeoutError; wire it into slow work with throwIfAborted and one abort listener.
FormData.entries yields every field and file as insertion-ordered pairs, while has/get/delete probe individual entries before a POST goes out.
Wire a two-way MessageChannel and transfer an ArrayBuffer through postMessage: the receiver decodes the bytes while the sender side reads length zero.
padEnd left-aligns names while padStart right-aligns numbers, producing fixed-width report columns; over-wide values are never truncated.
Promise.all rejects as soon as any member rejects, abandoning slower pending results, while allSettled waits for every member and aligns statuses by position.
Fold an array into a Map of per-key aggregates in one pass: the Map keeps first-seen order, and the object-spread version exposes a per-iteration copy trap.
structuredClone deep-copies Maps, Sets, and Dates that JSON.stringify drops, and its transfer option moves ArrayBuffer ownership instead of copying bytes.
Parse untrusted markup through a programmatic template: scripts never run, event-handler attributes stay inert, and content.cloneNode yields a disjoint tree.
Wire cleanup into scoping with using: the runtime calls Symbol.dispose on block exit in reverse order, and the error path disposes before the throw propagates.
dataclass fields declare mutable defaults through field(default_factory=list), giving every instance a fresh list instead of one shared across all of them.
Deduplicate records by choosing a key function and relying on dict insertion order: first-wins and last-wins are both one pass with no aux dedupe type.
fnmatch.filter matches shell-style patterns against filename lists, and fnmatchcase opts out of the platform case-insensitivity that fnmatch applies.
Freeze lookup tables with frozenset: mutation fails loudly at the source, hashing lets sets key dicts and appear inside other sets, and algebra still works.
functools.wraps copies __name__ and __doc__ onto the wrapper, so decorated functions keep their identity in logs, tracebacks, and help output.
Extended unpacking assigns first, *middle, last in one statement, and the starred slot absorbs zero or more items, so it never raises on short sequences.
Render grouped currency and number strings with locale.currency and locale.format_string so separators come from the locale database, not string surgery.
os.path.splitext returns name and extension as a pair by splitting only the final dot, while basename and dirname carve up the path around it.
Build and join pure path objects over in-memory trees: PurePosixPath does string algebra with no filesystem access, so manifests and reports stay deterministic.
Turn HTTP Range headers into safe (start, end) slices: suffix and open-ended forms clamp to the body size, and malformed ranges resolve to None.
statistics.mean, median, mode, and multimode give four different centers for one skewed list, and the disagreement itself is the signal worth reading.
Add timedelta to aware datetimes across a DST switch: wall-clock arithmetic keeps 7 hours but the UTC span changes — the booking-code contract.
Since Rust 2021, for loops consume arrays by value through IntoIterator; contrast iter() borrows with owned iteration and moves.
Demonstrate as conversions honestly: wide integers truncate, signed bit patterns reinterpret, char maps to its code point, floats saturate.
Compare tokens with eq_ignore_ascii_case to skip allocations, and know when to fall back to full Unicode to_lowercase for non-ASCII text.
Iterate a BTreeMap and get keys in ascending order every run, so reports and diffs are deterministic without collecting and sorting first.
Test characters with is_ascii_digit, is_alphanumeric, and friends, then partition or filter strings by those predicates in one pass.
Declare typed constants, const fns, and a static array sized by a const expression so the backoff table is computed during compilation.
Implement From for each upstream error so one error type owns every failure shape, and let the question mark operator convert automatically at each call site.
Write a manual Debug impl with debug_struct to redact secrets and mark unlisted fields with finish_non_exhaustive instead of leaking them.
File::create_new fails with ErrorKind::AlreadyExists when the path exists, giving you race-free exclusive creation for lock files and IDs.
Replace nested map-then-flatten chains with flat_map, turning one input into several outputs inside a single lazy iterator pass.
Fix decimal places with {:.N}, force signs, zero-pad widths, and switch to scientific notation with {:e} and {:E} format specifiers.
Render integers in binary, octal, and hex with the b, o, and x format specs, including zero padding and the # prefix variants.
Classify paths with fs::metadata: is_dir and len for existing entries, ErrorKind::NotFound for missing ones, no read of the file content.
Derive PartialEq, Eq, and Hash on a struct so whole-value lookups work in HashMap, then bucket repeated keys with the entry API.
Observe that HashMap visits entries in an order that can differ per run and per process, then produce stable output by sorting keys before iterating.
Parse length-prefixed frames with read_exact, which reports UnexpectedEof instead of a silent short read when the wire ends mid-frame.
Adapters behind an iterator can emit values after their first None; fuse() turns that first None into a permanent end so pipelines stay safe.
Right-pad short rows to a fixed width by chaining repeat_n onto the row iterator; the count saturates to zero when the row is already full.
Flatten a collection into one String with join, which works on slices of str, String, and even Option values, without hand-rolled loops or format! chains.
Rust labels live in the loop-type position ('search: for …) so break 'search unwinds every nesting level at once and continue 'rows discards one outer round.
Match against references and destructure through them so borrowed data stays in place, with bindings that keep ownership at the owner.
Group related types in an inline module, expose only what the API needs through pub and pub(crate), and reach it with use paths.
Read file_stem and extension, swap suffixes with set_extension and with_extension, and see None for files that never had one.
next_if consumes the next item only while a predicate holds, so parsers can peel digits or an exact character with no manual peek bookkeeping.
Store one string as Rc<str> and hand out cheap pointer clones to many structs, with strong_count confirming the single shared allocation.
Generate fixed-width separators, indentation, and repeated patterns with str::repeat, which allocates once instead of concatenating in a loop.
saturating_add, sub, and mul clamp at MIN and MAX instead of panicking or wrapping, unlike checked (Option) and overflowing (carry) variants.
Reuse a name with a new type through shadowing, contrast it with mut, and let block expressions produce values like if/else chains.
Cut byte ranges out of a String in place with drain, collect the removed part, and keep indices on char boundaries to avoid panics.
Test string membership with contains, starts_with, and ends_with, and remember that a pattern argument accepts chars as well as literal strings.
Convert between epoch offsets and unix seconds with duration_since, which returns Err instead of a negative duration when the clock runs backwards.
Declare a trait with required and default methods, implement it for multiple types, and call it through a generic function bound.
Clean user input with trim and trim_end before parse, because stray whitespace and line endings are the most common reason valid numbers fail to parse.
Use tuple keys in HashMap to count consecutive character pairs; derive ordering by collecting and sorting entries for stable output.
Give verbose types readable names with plain and generic aliases — no new type is created, so aliases stay interchangeable with the original.
Use insert and remove for order-preserving edits in the middle of a Vec, and know the O(n) shift cost that separates them from push, pop, and swap_remove.
Swap an archive table in as a partition with ALTER TABLE ATTACH PARTITION and detach it back out, moving whole datasets without copying rows.
Default ATTACH scans the new table to prove it satisfies the bounds; a pre-checked CHECK constraint lets PostgreSQL skip that validation scan.
Bucket timestamps into fixed-width strides with date_bin anchored at an origin, where date_trunc can only align to calendar units.
Delete the rows a grouped subquery selects with DELETE FROM ... USING, pruning expired sessions of over-limit users in one statement.
EXCEPT ALL keeps duplicate multiplicities, so a multiset difference reports how many copies of each row disappeared between two loads.
Diff two row snapshots with EXCEPT in both directions: rows only in the old load are removals, rows only in the new load are additions.
Combine scalar equality with an integer-range operator in one EXCLUDE USING gist constraint so adjacent booking slots may touch but never overlap.
Scope an exclusion constraint with WHERE so cancelled bookings stop blocking new ones while active overlaps still fail.
Point at the first row of each partition with first_value, and keep the current row intact — unlike aggregate functions that collapse rows.
Clamp numbers into bounds with GREATEST and LEAST: chain both for a range clamp; PostgreSQL ignores NULL inputs, returning NULL only when all are NULL.