View source code
Display the source code in std/algorithm/searching.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.algorithm.searching.balancedParens

Checks whether r has "balanced parentheses", i.e. all instances of lPar are closed by corresponding instances of rPar. The parameter maxNestingLevel controls the nesting level allowed. The most common uses are the default or 0. In the latter case, no nesting is allowed.

bool balancedParens(Range, E) (
  Range r,
  E lPar,
  E rPar,
  size_t maxNestingLevel = size_t.max
)
if (isInputRange!Range && is(typeof(r.front == lPar)));

Parameters

NameDescription
r The range to check.
lPar The element corresponding with a left (opening) parenthesis.
rPar The element corresponding with a right (closing) parenthesis.
maxNestingLevel The maximum allowed nesting level.

Returns

true if the given range has balanced parenthesis within the given maximum nesting level; false otherwise.

Example

auto s = "1 + (2 * (3 + 1 / 2)";
assert(!balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(balancedParens(s, '(', ')'));
s = "1 + (2 * (3 + 1) / 2)";
assert(!balancedParens(s, '(', ')', 0));
s = "1 + (2 * 3 + 1) / (2 - 5)";
assert(balancedParens(s, '(', ')', 0));
s = "f(x) = ⌈x⌉";
assert(balancedParens(s, '⌈', '⌉'));

Authors

Andrei Alexandrescu

License

Boost License 1.0.