java的“lookingat”regex函数?

bihw5rsg  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(274)

我正在尝试将这个脚本从java移植到go。此脚本使用 lookingAt 在几个地方起作用。似乎这个函数只是用来检查字符串是否以与模式匹配的字符串开头
尝试将输入序列与模式匹配,从区域的开头开始。与matches方法一样,这个方法总是从区域的开始开始;与该方法不同,它不需要匹配整个区域。
如果匹配成功,则可以通过start、end和group方法获得更多信息。
当且仅当输入序列的前缀匹配此匹配器的模式时返回:true
围棋有没有类似的功能 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

但我觉得这是可以改进的。

nimxete2

nimxete21#

在看了一些示例和其他一些示例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

}


#### 示例

(示例) `lookingAt` 取自Geeksforgeks)
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")
}

Playground:https://play.golang.org/p/mjt9uauy4u3

相关问题