duan5991518
2017-05-21 21:49
浏览 812
已采纳

Golang正则表达式提取2个定界符之间的文本-包括定界符

As stated in the title I have an program in golang where I have a string with a reoccurring pattern. I have a beginning and end delimiters for this pattern, and I would like to extract them from the string. The following is pseudo code:

string := "... This is preceding text
PATTERN BEGINS HERE (
pattern can continue for any number of lines...
);
this is trailing text that is not part of the pattern"

In short what I am attempting to do is from the example above is extract all occurrences of of the pattern that begins with "PATTERN BEGINS HERE" and ends with ");" And I need help in figuring out what the regex for this looks like.

Please let me know if any additional info or context is needed.

图片转代码服务由CSDN问答提供 功能建议

如标题中所述,我在golang中有一个程序,其中有一个带有重复模式的字符串。 我有此模式的开始和结束定界符,我想从字符串中提取它们。 以下是伪代码:

  string:=“ ...这是前面的文字
PATTERN BEGINS HERE(
模式可以继续任意行... 
  ); 
这是不属于模式“ 
   
 
 

的部分的结尾文本”简而言之,我试图从上面的示例中提取所有出现的 以“ PATTERN BEGINS HERE”开头并以“)结尾的模式的样式; 我需要帮助找出正则表达式的外观。

请让我知道是否需要其他信息或上下文。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dtr32787 2017-05-21 23:11
    已采纳

    The regex is:

    (?s)PATTERN BEGINS HERE.*?\);
    

    where (?s) is a flag to let .* match multiple lines (see Go regex syntax).

    See demo

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongyijing2353 2017-06-27 11:05

    Not regex, but works

    func findInString(str, start, end string) ([]byte, error) {
        var match []byte
        index := strings.Index(str, start)
    
        if index == -1 {
            return match, errors.New("Not found")
        }
    
        index += len(start)
    
        for {
            char := str[index]
    
            if strings.HasPrefix(str[index:index+len(match)], end) {
                break
            }
    
            match = append(match, char)
            index++
        }
    
        return match, nil
    }
    

    EDIT: Best to handle individual character as bytes and return a byte array

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题