登录
首页 >  Golang >  Go问答

Java中用于匹配开头的正则表达式函数是什么?

来源:stackoverflow

时间:2024-02-17 20:24:25 319浏览 收藏

本篇文章给大家分享《Java中用于匹配开头的正则表达式函数是什么?》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在尝试将此脚本从 java 移植到 go。该脚本在多个地方使用了 lookingat 函数。看来这个函数只是为了检查字符串是否以与模式匹配的字符串开头

尝试从区域的开头开始与模式匹配输入序列。 与 matches 方法一样,此方法始终从区域的开头开始;与该方法不同的是,它不需要匹配整个区域。 如果匹配成功,则可以通过 start、end 和 group 方法获得更多信息。 返回: true 当且仅当输入序列的前缀与此匹配器的模式匹配时

go 的 regexp 包中是否有类似的功能(我没有看到类似的功能),如果没有,如何实现它?

现在,我的最佳实现如下所示:

regex := "ThePrefix"
stringToBeMatched := "ThePrefix-The rest of the string"

pattern := regexp.MustCompile(regex)
idxs := pattern.FindStringIndex(stringToMatch)

lookingAt := len(idxs) > 0 && idxs[0] == 0

但我觉得这可以改进。


解决方案


在查看了一些示例和其他一些示例 go 代码之后,我提出了一个更实用的实现,它还将为您提供 java 实现中可用的开始、结束位置。您还可以使用开始、结束位置来检索 stringtomatch[start:end]

// lookingat attempts to match the input sequence, starting at the beginning of the region, against the pattern
// without requiring that the entire region be matched and returns a boolean indicating whether or not the
// pattern was matched and the start and end indexes of where the match was found.
func lookingat(pattern *regexp.regexp, stringtomatch string) (bool, int, int) {
    idxs := pattern.findstringindex(stringtomatch)
    var matched bool
    var start int = -1
    var end   int = -1

    matched = len(idxs) > 0 && idxs[0] == 0
    if len(idxs) > 0 {
        start = idxs[0]
    }
    if len(idxs) > 1 {
        end = idxs[1]
    }

    return matched, start, end
}

示例

lookingat 的示例取自 GeeksForGeeks

java

// get the regex to be checked 
string regex = "geeks"; 
  
// create a pattern from regex 
pattern pattern 
    = pattern.compile(regex); 
  
// get the string to be matched 
string stringtobematched 
    = "geeksforgeeks"; 
  
// create a matcher for the input string 
matcher matcher 
    = pattern 
          .matcher(stringtobematched); 
  
boolean matched = matcher.lookingat();
int start = matcher.start();
int end = matcher.end();

if (matched) {
    system.out.println("matched, " + start + " - " + end);
} else {
    system.out.println("not matched");
}

在 go 中:

regex := "Geeks"
stringToBeMatched := "GeeksForGeeks"

pattern := regexp.MustCompile(regex)
    
matched, start, end := lookingAt(pattern, stringToBeMatched)
    
if matched {
    fmt.Printf("matched, %v - %v\n", start, end)
} else {
    fmt.Println("not matched")
}

演示:https://play.golang.org/p/MjT9uaUY4u3

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Java中用于匹配开头的正则表达式函数是什么?》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>