Мне нужно отделить целое число от строки. Итак, я могу разделить «abc10» как abc в token1 и 10 в token2, используя ниже в golang.
const regexString = "([A-Z|a-z]+)"
var mystr = regexp.MustCompile(regexString)
.....
token := "abc10"
token1 := ""
token2 := ""
matches := mystr.FindStringSubmatch(token)
switch matchLen {
case 0, 1:
token1 = ""
token2 = token
case 2:
token1 = matches[1]
_, token2, _ = strings.Cut(token, matches[1])
}
Но столкнулся с проблемой: как сделать то же самое, если ввод имеет форму ниже: токен: «привет abc1» --> токен1: «привет abc», токен2: 1 или жетон: «окончательный счет3/2» --> жетон1: «окончательный подсчет», жетон2: «3/2»
Попробуйте перебрать строку назад, чтобы определить, где начинается последняя числовая или дробная часть:
package main
import (
"fmt"
"unicode"
)
// SeparateToken tries to separate a string into two parts:
// - token1 (the part before the last numeric or fractional part)
// - token2 (the last numeric or fractional part)
func SeparateToken(token string) (string, string) {
n := len(token)
for i := n - 1; i >= 0; i-- {
if !unicode.IsDigit(rune(token[i])) && token[i] != '/' {
return token[:i+1], token[i+1:]
}
}
// If no numeric or fractional part is found, return the entire token as token1.
return token, ""
}
func main() {
testCases := []string{
"abc10",
"hello abc1",
"final count3/2",
"xyz",
"apple 32 banana 10",
}
for _, testCase := range testCases {
token1, token2 := SeparateToken(testCase)
fmt.Printf("%q -> token1: %q, token2: %q\n", testCase, token1, token2)
}
}
Выход:
"abc10" -> token1: "abc", token2: "10"
"hello abc1" -> token1: "hello abc", token2: "1"
"final count3/2" -> token1: "final count", token2: "3/2"
"xyz" -> token1: "xyz", token2: ""
"apple 32 banana 10" -> token1: "apple 32 banana ", token2: "10"
Try on Go Playground