解析正则表达式-(不够) [英] parsing regex - (Not enough )'s

查看:72
本文介绍了解析正则表达式-(不够)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用书建立了一个很小的数据库,并试图用C#中的正则表达式获取书名,作者和书年,但发生了错误.

I made a tiny database with books and trying to get titles, authors and year of book with regex in c# but error occured.

数据库如下:

Eragon // Christopher Paolini // 2005

The Fellowship of the Ring // J. R. R. Tolkien // 1954

和代码:

Regex r = new Regex(@"(?<title>(.*)//" +
                    @"(?<author>(.*)//" +
                    @"(?<year>(.*)$");

错误:

parsing "(?<tytul>(.*)//(?<autor>(.*)//(?<rok>(.*)$" - Not enough )'s.

推荐答案

您忘记关闭所有命名的捕获组.

You forget to close all the named capturing groups.

@"(?<tytul>(.*))//(?<autor>(.*))//(?<rok>(.*))$"
               ^               ^             ^

演示

通过首先将贪婪的量词.* 变为非贪婪的.*?,可以避免

By turning the greedy quantifiers .* at the first to non-greedy .*? would avoid backtracking.

@"^(?<tytul>(.*?))//(?<autor>(.*?))//(?<rok>(.*))$"

这篇关于解析正则表达式-(不够)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆