This question already has answers here:
Find all string matches with Regex golang
(1 answer)
Regex find many word in the string
(1 answer)
How to iterate through regex matching groups
(1 answer)
Closed 4 months ago.
my strings:
12345:cluster/ecs52v-usw2-tst",
12345:cluster/test32-euw1-stg",
The output I'm looking for is:
ecs52v-usw2-tst
test32-euw1-stg
I have multiple cluster names that I'm trying to capture in a slice
I've gotten it in ruby (?<=\/)(.*(tst|stg|prd))(?=") but I'm having trouble in golang.
https://go.dev/play/p/DyYr3igu2CF
You could use FindAllStringSubmatch to find all submatches.
func main() {
var re = regexp.MustCompile(`(?mi)(/(.*?)")`)
var str = `cluster/ecs52v-usw2-tst",
cluster/ecs52v-usw2-stg",
cluster/ecs52v-usw2-prd",`
matches := re.FindAllStringSubmatch(str, -1)
for _, match := range matches {
fmt.Printf("val = %s \n", match[2])
}
}
Output
val = ecs52v-usw2-tst
val = ecs52v-usw2-stg
val = ecs52v-usw2-prd
https://go.dev/play/p/_LRVYaM2r7z
package main
import (
"fmt"
"regexp"
)
func main() {
var re = regexp.MustCompile(`(?mi)/(.*?)"`)
var str = `cluster/ecs52v-usw2-tst",
cluster/ecs52v-usw2-stg",
cluster/ecs52v-usw2-prd",`
for i, match := range re.FindAllStringSubmatch(str, -1) {
fmt.Println(match[1], "found at line", i)
}
}
Related
This question already has answers here:
Lazy quantifier {,}? not working as I would expect
(3 answers)
Closed 2 years ago.
Here is a simple regular expression:
package main
import (
"fmt"
"regexp"
)
const data = "abcdefghijklmn"
func main() {
r, err := regexp.Compile(".{1,6}")
if err != nil {
panic(err)
}
for _, d := range r.FindAllIndex([]byte(data), -1) {
fmt.Println(data[d[0]:d[1]])
}
}
And we know it is greedy:
abcdef
ghijkl
mn
Now, we can add a ? after the expression to make it non greedy:
package main
import (
"fmt"
"regexp"
)
const data = "abcdefghijklmn"
func main() {
r, err := regexp.Compile(".{1,6}?")
if err != nil {
panic(err)
}
for _, d := range r.FindAllIndex([]byte(data), -1) {
fmt.Println(data[d[0]:d[1]])
}
}
And we can get:
a
b
c
d
e
f
g
h
i
j
k
l
m
n
However, if we add other chars after the expression, it becomes greedy:
package main
import (
"fmt"
"regexp"
)
const data = "abcdefghijklmn"
func main() {
r, err := regexp.Compile(".{1,6}?k")
if err != nil {
panic(err)
}
for _, d := range r.FindAllIndex([]byte(data), -1) {
fmt.Println(data[d[0]:d[1]])
}
}
And we get:
efghijk
So why it becomes greedy if we add a char after it?
Adding a lazy quantifier after a repetition count changes it from matching as many as possible, to as few as possible.
However, this does not change the fact that the string must be processed serially. This is where your two cases differ:
.{1,6}? returns one character at a time because this is the fewest matches as the string is being processed. The lazy quantifier lets the engine match after a single character, not needing to keep processing the string.
.{1,6}?k has to skip over abcd to get a match, but it then finds the substring starting at e to be a match. A lazy quantifier does not let the engine move to the next character in the string.
In short: matching from the current position takes precedence over moving to the next position in the hope of a smaller match.
As for your question about making it lazy again, you can't. You'll have to find a different regular expression for the output you want.
This question already has answers here:
Match exact string
(3 answers)
Closed 3 years ago.
I'm trying to write a program that prints the invalid part or parts of an IPv4 address from terminal input.
Here is my code:
package chapter4
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"time"
)
func IPV4() {
var f *os.File
f = os.Stdin
defer f.Close()
scanner := bufio.NewScanner(f)
fmt.Println("Exercise 1, Chapter 4 - Detecting incorrect parts of IPv4 Addresses, enter an address!")
for scanner.Scan() {
if scanner.Text() == "STOP" {
fmt.Println("Initializing Level 4...")
time.Sleep(5 * time.Second)
break
}
expression := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
matchMe, err := regexp.Compile(expression)
if err != nil {
fmt.Println("Could not compile!", err)
}
s := strings.Split(scanner.Text(), ".")
for _, value := range s {
fmt.Println(value)
str := matchMe.FindString(value)
if len(str) == 0 {
fmt.Println(value)
}
}
}
}
My thought process is that for every terminal IP address input, I split the string by '.'
Then I iterate over the resulting []string and match each value to the regular expression.
For some reason the only case where the regex expression doesn't match is when there are letter characters in the input. Every number, no matter the size or composition, is a valid match for my expression.
I'm hoping you can help me identify the problem, and if there's a better way to do it, I'm all ears. Thanks!
Maybe, this expression might be closer to what you might have in mind:
^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$
Test
package main
import (
"regexp"
"fmt"
)
func main() {
var re = regexp.MustCompile(`(?m)^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$`)
var str = `127.0.0.1
192.168.1.1
192.168.1.255
255.255.255.255
0.0.0.0
1.1.1.01
30.168.1.255.1
127.1
192.168.1.256
-1.2.3.4
3...3`
for i, match := range re.FindAllString(str, -1) {
fmt.Println(match, "found at index", i)
}
}
The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.
Reference:
Validating IPv4 addresses with regexp
RegEx Circuit
jex.im visualizes regular expressions:
I am pretty sure that your expression needs anchors or the last part of it will match any single digit and succeed. Try using ^ on the front and $ on the back.
I have these strings and they can come in a variety of ways such as:
id=PS\\ Old\\ Gen, value=34 and id=Code\\ Cache,value=22 etc.
I would like a regex that would extract anything after the = to the , so basically: PS\\ Old\\ Gen and Code\\ Cache etc.
I have written the following regex but can't seem to get the last word before the ,.
(([a-zA-z]+)\\{2})+
Any thoughts? This is for go language.
You can use this regex and capture your text from group1,
id=([^,=]*),
Explanation:
id= - Matches id= literally
([^,=]*) - Matches any character except , or = zero or more times and captures in first grouping pattern
, - Matches a comma
Demo
Sample Go codes,
var re = regexp.MustCompile(`id=([^,=]*),`)
var str = `id=PS\\ Old\\ Gen, value=34 id=Code\\ Cache,value=22`
res := re.FindAllStringSubmatch(str, -1)
for i := range res {
fmt.Printf("Match: %s\n", res[i][1])
}
Prints,
Match: PS\\ Old\\ Gen
Match: Code\\ Cache
Does something like id=([^,]+), do the trick?
Capture group no.1 will contain your match. See this in action here
How about that? SEE REGEX
package main
import (
"regexp"
"fmt"
)
func main() {
var re = regexp.MustCompile(`(?mi)id=([^,]+)`)
var str = `id=PS\\ Old\\ Gen, value=34 and id=Code\\ Cache,value=22`
for i, match := range re.FindAllString(str, -1) {
fmt.Println(match, "found at index", i)
}
}
This question already has answers here:
Differences between Javascript regexp literal and constructor
(2 answers)
Javascript RegEx Not Working [duplicate]
(1 answer)
Closed 4 years ago.
I have the following RegEx that works well in Java Script but not in JScript. The only difference I found between the 2 is the that JScript uses /expression/ and tried it with no luck. I need to match specific string date format.
var pattern = "/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))T(00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/";
var regexpattern = new RegExp(pattern);
var str = "2018-02-28T17:05:10";
var res = regexpattern.test(str);
//var res = str.match(pattern);
if ( res != null)
{
Log.Message("Test worked ");
}
else
{
Log.Message("did not");
}
EDIT:
It should be declared as:
var pattern = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))T(00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/;
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I would like to extract two numbers for a strings by regex "[0-9]+"
var str = "ABcDEFG12345DiFKGLSG938SDsFSd"
What I want to extract is "12345" and "938".
But I am not sure how to do so in Kotlin.
This should work:
import java.util.regex.Matcher
import java.util.regex.Pattern
fun main(args:Array<String>) {
val p = Pattern.compile("\\d+")
val m = p.matcher("ABcDEFG12345DiFKGLSG938SDsFSd")
while (m.find())
{
println(m.group())
}
}
Pattern.compile("\\d+"), it will extract the digits from the expression.