在Symfony2配置TreeBuilder中使用正则表达式验证?

I'm using Symfony2's tree builder, which I see has some basic validation rules as described here: http://symfony.com/doc/current/components/config/definition.html#validation-rules

Is there a way to also validate by regular expression?

Here's how I'm doing it at the moment, but I am not sure if this is 'best practice'. The config item I want to validate is root_node.

config.yml

my_bundle:
    root_node: /some/path    # this one is valid

Configuration.php

$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('my_bundle');

$rootNode
    ->children()
        ->scalarNode('root_node')
             ->end()
        ->end()
    ->end();

return $treeBuilder;

MyBundleExtension.php

$nodePattern = '#/\w+(/w+)*#';
if (! preg_match($nodePattern, $config['root_node'])) {
    throw new \Exception("root_node is not valid: must match the pattern: $nodePattern");
}

So, what I'm really after is a TreeBuilder method:

->validate()->ifNotMatchesRegex()->thenInvalid()

or, failing that, the best approach to enforce my validation rule.

What you can do is use the ifTrue method with your custom function. Something like this:

$rootNode
    ->children()
        ->scalarNode('root_node')
            ->validate()
            ->ifTrue(function ($s) {
                return preg_match('#/\w+(/\w+)*#', $s) !== 1;
            })
                ->thenInvalid('Invalid path')
            ->end()
       ->end()
   ->end();

Note the slight modification I made to your regex.