过于贪婪的正则表达式问题

发布于 2024-10-02 15:04:53 字数 1470 浏览 1 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

┊风居住的梦幻卍 2024-10-09 15:04:53
Regex TitleRegex = new Regex(@"[A-Z].* - ([0-9]{1,2}) [A-Z]");

您正在捕获 .,它通常匹配除换行符之外的所有内容。我将 {1,2} 量词放在那里,这意味着它将匹配 0-99。更改它以满足您的要求(或者您可以将其保留为0或更多*)。

您还可以使用 \d 而不是 [0-9] 吗?速记通常是一件好事:)

Regex TitleRegex = new Regex(@"[A-Z].* - ([0-9]{1,2}) [A-Z]");

You are capturing the . which generally is match all except new lines. I put the {1,2} quantifier there, meaning it will match 0-99. Change that to suit your requirements (or you could just leave it as 0 or more *).

Could you also use \d instead of [0-9]. Shorthand is generally a good thing :)

一世旳自豪 2024-10-09 15:04:53

之所以包含这些字母,是因为您在将 .* 添加到捕获组时要求提供这些字母。尝试使用 ([0-9]+) 或更好的 (\d+)

The letters are included because you asked for them when you added .* to the capture group. Try just ([0-9]+) or better (\d+)

浮萍、无处依 2024-10-09 15:04:53

答案是你似乎滥用了量词;

[0-9].*

该部分模式与任何单个数字 (0-9) 匹配一次,然后匹配任何字符 (.) 0 次或多次 (*)

删除星号前的点。

[0-9]*

The answer is that you appear to be misusing the quantifiers;

[0-9].*

That partial pattern matches any single digit (0-9) once, and then also any character at all (.) 0 or more times (*)

Remove the dots before the asterisks.

[0-9]*
厌味 2024-10-09 15:04:53

更改为:

"[A-Z].* - ([0-9]?) [A-Z]"

当您使用 [0-9].* 时,它会搜索一个数字加 0 或多个符号,使用 [0-9]+ 会搜索一个或多个符号该特定位置上的整数。如果您确定不会超过 3 个整数,那么您可以使用 [0-9]{1,3} 或任意数量的 4,5 等。

Change to:

"[A-Z].* - ([0-9]?) [A-Z]"

When you use [0-9].* it searches for one number plus 0 or many symbols, using [0-9]+ gives you one or more integers on that specific place. If you are sure there wont be more than lets say 3 integers so you can use [0-9]{1,3} or as much as you want 4,5,etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文