如何使用正则表达式提取子字符串,仅给出索引?

5

有没有一种方法可以仅根据子字符串的起始和结束位置的索引提取字符串/句子的一部分呢? 例如:"this is an example00001. and so on.",我需要使用正则表达式从位置10到15获取子字符串(即,examp)。


2
你为什么要使用正则表达式呢?你所在的平台没有标准库中的子字符串函数吗? - Jim Lewis
2
@Jim Lewis,你是对的...我使用的工具只接受正则表达式 :( - user3366706
2个回答

2

使用向后查找并锚定到开头。

以位置10至15为例:

(?<=^.{10}).{5}

如果不支持向后查找,请使用以下组的第一个:
^.{10}(.{5})

它能工作,但你能解释一下发生了什么吗?或者建议我一些好的链接来理解这个。谢谢。 - user3366706
谢谢Bohemian,你能告诉我如何从后面提取吗?比如我有一个字符串"GetIndicatorsByAnalysisProcessIDServlet service",我只想提取"GetIndicatorsByAnalysisProcess"。 - Nagappa L M
@feelgoodandprogramming 应该作为一个新问题提出,而且不明显在哪里停止 - 停在 ID,停在结尾的第17个字符,还是其他什么地方?(但尝试使用 ^.*(?=ID) - Bohemian

1

我认为您需要从位置11开始获取所需的匹配项。以下是一个示例:

$ cat input.txt
This is an example00001. and so on.
$ sed -r 's|(.{10})(.{5})(.*)|\2|' input.txt
 exam
$ sed -r 's|(.{11})(.{5})(.*)|\2|' input.txt
examp

这是什么意思:
    -r      extended regular expressions (only on gnu sed) 
    s       for substitution  
    |       for separator  
    (.{11}) for the first group of any 11 characters (you might want 10)  
    (.{5})  for the second group of any 5 characters 
    (.*)    for any other character, not really needed though  
    \2      for replacing with the second group

你可能需要在正则表达式中使用 ^ 和 $ 字符来匹配行的开头和结尾。

工具中不允许使用编号的返回引用或调用 :( - user3366706

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接