繁体   English   中英

Java 的“lookAt”正则表达式 function?

[英]Java's “lookingAt” regex function?

我正在尝试将此脚本从 Java 移植到 Go。 这个脚本在几个地方使用了lookingAt function。 似乎这个 function 只是为了检查字符串是否以与模式匹配的字符串开头

尝试从区域的开头开始匹配输入序列与模式。 和matches方法一样,这个方法总是从区域的开头开始; 与该方法不同的是,它不需要匹配整个区域。

如果匹配成功,则可以通过 start、end 和 group 方法获取更多信息。

返回: true 当且仅当输入序列的前缀匹配此匹配器的模式

Go 的正则regexp package 中是否有类似的 function 可用(我没有看到类似的东西),如果没有,如何实现它?

现在,我最好的实现是这样的:

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 实现中可用的开始、结束位置。 您可以使用开始、结束位置来检索group位置,方法是使用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
}

例子

(从GeeksForGeeks获取的lookingAt示例)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM