正则表达式匹配之前已解析过的多个字符
假设我有一个文件,其中包含如下所示的行:
"7sunrIsEfoo"
"10ecological09"
"3bedtime"
每行都以代表数字 n 的数字开头。我想匹配它后面的n个字符。输出应该是:
sunrIsE
ecological
bed
有没有办法使用正则表达式来做到这一点?我的第一次尝试是:
([0-9]*)[a-zA-Z]{\1}
但似乎不起作用。
Say I have a file that contains lines that look like this:
"7sunrIsEfoo"
"10ecological09"
"3bedtime"
Each line starts with numeral(s) that represent number n. I want to match the n characters following it. The output should be:
sunrIsE
ecological
bed
Is there a way to do this using a regular expression? My first attempt was:
([0-9]*)[a-zA-Z]{\1}
but it doesn't seem to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这对于正则表达式来说是不可能的。
([0-9]*)
只是将数字“记住”为子字符串:它们不能用于数字。That's not possible with regex.
([0-9]*)
just "remembers" the digits as a substring: they can't be used numerically.在 Ruby 中,您可以使用:
result = string[/(\d+)([a-zA-Z]+)/,2][0,$1.to_i]
它会给您预期的结果结果。
In Ruby, you could use:
result = string[/(\d+)([a-zA-Z]+)/,2][0,$1.to_i]
It will give you the expected result.
正则表达式不太适合这项任务。他们没有构建解释数字的方法。
您可以通过使用等来使用(混乱的)解决方法
(尽管您最好使用相反的顺序,否则在达到 11 时您会遇到问题)。请注意,除非您确实没有其他方法,否则不应该使用此方法=)
Regular expressions are not well suited for this task. They have no built it way to interpret numbers.
You could use a (messy) workaround by using
and so on (Though you'd better use the reverse order, otherwise you'll have problems when reaching 11). Note that you should not use this method unless you really really have no other way =)
这是在 Perl 中执行此操作的一种方法:
输出:
Here is a way to do it in Perl:
output: