Given the following Groovy:
static void main(String[] args) {
String permission = "[fizz]:[index]"
String regex = "[fizz]:[*]"
if((permission =~ regex).matches()) {
println "We match!"
} else {
println "We don't match!"
}
}
The result is: "We don't match!". How is this possible?!?
You need to escape square brackets and, to match index, you need to use .*, which means "any char, any number of times". Also, groovy's slashy string syntax helps:
String permission = "[fizz]:[index]"
String regex = /\[fizz]:\[.*]/
assert (permission =~ regex).matches()
assert permission ==~ regex
Update: you can use double quote string by escaping square brackets twice:
String regex = "\\[fizz]:\\[.*]"
Related
i am new to scala and hate regex :D
cuurently i am debuggig a piece of code
def validateReslutions(reslutions: String): Unit = {
val regex = "(\\d+-\\d+[d,w,m,h,y],?)*"
if (!reslutions.matches(regex)) {
throw new Error("no match")
} else {
print("matched")
}
}
validateReslutions(reslutions = "(20-1w,100-1w)")
}
the problem is it produces no match for this input , so how to correct the regex to match this input
Your (20-1w,100-1w) string contains a pair of parentheses at the start and end, and the rest matches with your (\d+-\d+[d,w,m,h,y],?)* regex. Since String#matches requires a full string match, you get an exception.
Include the parentheses patterns to the regex to avoid the exception:
def validateReslutions(reslutions: String): Unit = {
val regex = """\((\d+-\d+[dwmhy],?)*\)"""
if (!reslutions.matches(regex)) {
throw new Error("no match")
} else {
print("matched")
}
}
validateReslutions(reslutions = "(20-1w,100-1w)")
// => matched
See the Scala demo.
Note the triple quotes used to define the string literal, inside which you can use single backslashes to define literal backslash chars.
Also, mind the absence of commas in the character class, they match literal commas in the text, they do not mean "or" inside character classes.
I'm making a method in Kotlin using Regex that checks if a string contains one or more of certain pronouns (such as "I", "we", "you", etc). E.g. "We are a tech company" should be a match, "Web is for spiders" should not be a match.
I tried with this code:
fun main() {
val text = "We are testing!"
val regex = "/\b(i|you|we)\b/g".toRegex()
if (regex.containsMatchIn(text.lowercase())) {
println("match")
} else {
println("no match")
}
}
, but it prints "no match".
Kotlin (and Java) regexps are defined with string literals, and not regex literals, i.e. when you add / at the start and /g (or just /) at the end of the pattern, you actually add them to the pattern string.
You can use the following fix:
val text = "We are testing!"
val regex = """(?i)\b(i|you|we)\b""".toRegex()
if (regex.containsMatchIn(text)) {
println("match")
} else {
println("no match")
}
The """(?i)\b(i|you|we)\b""" is equal to "(?i)\\b(i|you|we)\\b", the former treats backslashes as literal chars.
Note you do not need to use .lowercase(), the (?i) case insensitive modifier will make matching case insensitive.
See the online Kotlin demo.
I don't understand how I should use regular expressions in groovy despite it having several operators to work with it.
import java.util.regex.*
def line = "Line with 1 digits"
Pattern p = Pattern.compile("\\d+")
Matcher m = p.matcher(line)
if (m.find()) { // true
println "found digit"
} else {
println "not found digit"
}
if (line ==~ /\\d+/) { // false
println "found"
} else {
println "not found"
}
if (line =~ /\\d+/) { // false
println "found"
} else {
println "not found"
}
In my example in java code it found that there is a digit in the string successfully. However in groovy it was not able to do it.
What is wrong?
See this slashy string reference:
Slashy strings are particularly useful for defining regular expressions and patterns, as there is no need to escape backslashes.
You need to use a single backslash with \d in /\d+/ Groovy slashy strings defining a regex.
if (line =~ /\d+/) { // false
println "found"
} else {
println "not found"
}
The line =~ /\d+/ checks if a line contains one or more digits.
The line2 ==~ /\d+/ checks if the whole string consists of only digits.
See IDEONE demo.
Also, see some more information about using regex in Groovy at regular-expressions.info.
You can use find
if (line.find(/\d+/)) {
println "found"
} else {
println "not found"
}
Just as an addition if you need a Boolean, like
def myBool = line.find(/\d+/)
this returns null, if it cannot find it - and the number it matches otherwise.
Same with line =~ /\d+/ that returns a java.util.regex.Matcher.
So to get a Boolean directly you can for example extend the Regex and use matches:
def myBool = line..matches(/.*\d+.*/))
It is well established that "|" in a regex is the "OR" operator. So when I run this:
static void main(String[] args) {
String permission = "[fizz]:[index]"
if((permission =~ /\[fizz|buzz]:\[.*]/).matches()) {
println "We match!"
} else {
println "We don't match!"
}
}
...then why does it print "We don't match!"???
The regex \[fizz|buzz]:\[.*] matches:
\[fizz - literal [ followed by fizz
| - OR operator....
buzz]:\[ - matches literal buzz]:[
.* - any character but a newline, as many times as possible, greedy
] - a literal ].
I think you need to re-group the alternatives:
if((permission =~ /\[(?:fizz|buzz)]:\[[^\]]*]/).matches()) {
Here, \[(?:fizz|buzz)]:\[[^\]]*] will match a [, then either fizz or buzz without capturing the words, then ]:[, [^\]]* will match 0 or more any characters but a ] and then ].
Check the regex101 demo. Also checked at OCP Regex Visualizer:
I am trying to decide whether a simple regular expression matches a string in Groovy. Here's my task in gradle. I tried to match with 2 different ways I found on the net, but neither of them works. It always prints out "NO ERROR FOUND"
task aaa << {
String stdoutStr = "bla bla errors found:\nhehe Aborting now\n hehe"
println stdoutStr
Pattern errorPattern = ~/error/
// if (errorPattern.matcher(stdoutStr).matches()) {
if (stdoutStr.matches(errorPattern)) {
println "ERROR FOUND"
throw new GradleException("Error in propel: " + stdoutStr)
} else {
println "NO ERROR FOUND"
}
}
(?s) ignores line breaks for .* (DOTALL) and the regexp there means a full match. so with ==~ as shortcut it's:
if ("bla bla errors found:\nhehe Aborting now\n hehe" ==~ /(?s).*errors.*/) ...
if (errorPattern.matcher(stdoutStr).matches()) {
The matches() method requires the whole string to match the pattern, if you want to look for matching substrings use find() instead (or just if(errorPattern.matcher(stdoutStr)) since Groovy coerces a Matcher to Boolean by calling find).