Regex is not matching in Scala - regex

I want to split up a camelCase string with spaces.
"ClassicalMusicArtist" -> "Classical Music Artist"
I should be able to do this by replacing "/([a-z](?=[A-Z]))/g" with "$1 " (regex101).
But my regex is not getting any matches:
val regex = "/([a-z](?=[A-Z]))/g".r
val s = "ClassicalMusicArtist"
regex.replaceAllIn(s, "$1 ") // -> Returns "ClassicalMusicArtist"
regex.findFirstIn(s) // -> Returns None
What am I doing wrong? I used the regex in another language with success and can't figure out why I am not getting any matches.

Ok I figured it out.
In scala the regex has to be val regex = "([a-z](?=[A-Z]))".r without the leading / and the modifier.

Related

Dart RegEx is not splitting String

Im a fresher to RegEx.
I want to get all Syllables out of my String using this RegEx:
/[^aeiouy]*[aeiouy]+(?:[^aeiouy]*\$|[^aeiouy](?=[^aeiouy]))?/gi
And I implemented it in Dart like this:
void main() {
String test = 'hairspray';
final RegExp syllableRegex = RegExp("/[^aeiouy]*[aeiouy]+(?:[^aeiouy]*\$|[^aeiouy](?=[^aeiouy]))?/gi");
print(test.split(syllableRegex));
}
The Problem:
Im getting the the word in the List not being splitted.
What do I need to change to get the Words divided as List.
I tested the RegEx on regex101 and it shows up to Matches.
But when Im using it in Dart with firstMatch I get null
You need to
Use a mere string pattern without regex delimiters in Dart as a regex pattern
Flags are not used, i is implemented as a caseSensitive option to RegExp and g is implemented as a RegExp#allMatches method
You need to match and extract, not split with your pattern.
You can use
String test = 'hairspray';
final RegExp syllableRegex = RegExp(r"[^aeiouy]*[aeiouy]+(?:[^aeiouy]*$|[^aeiouy](?=[^aeiouy]))?",
caseSensitive: true);
for (Match match in syllableRegex.allMatches(test)) {
print(match.group(0));
}
Output:
hair
spray

Matcher of Regex expression is false while the expression, pattern and string are all valid

I am using a regex regular expression like so:
#Test
fun timePatternFromInstantIsValid() {
val instantOfSometimeEarlier = Instant.now().minus(Duration.ofMinutes((1..3).random().toLong()))
val timeOfEvent = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneId.of("UTC")).format(instantOfSometimeEarlier)
val regex = "(\\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))T(?:(?:([01]?\\d|2[0-3]):)?([0-5]?\\d):)?([0-5]?\\d)"
val acceptedDatePattern: Pattern = Pattern.compile(regex)
val matcher: Matcher = microsoftAcceptedDatePattern.matcher(timeOfEvent)
val isMatchToAcceptedDatePattern: Boolean = matcher.matches()
print(isMatchToAcceptedDatePattern)
}
isMatchToAcceptedDatePattern for some reason is returning false which probably indicates something is wrong in my regex BUT, when checking it on multiple regex websites I'm getting a valid match. any ideas why?
try it yourself:
https://www.regextester.com/ or here:
https://regex101.com/
my regex - raw (as in the websites):
(\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))T(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)?([0-5]?\d)
pattern example returned like this (it gets returned without the " ' " near the "T"):
2021-04-01T11:12:51 (when I debug this is what I get)
date pattern:
yyyy-MM-ddTHH:mm:ss
could someone inlight me please?
You use matcher.matches() which is like pre- and appending ^ resp. $ to your regex. Such a regex won't work.
Instead you should either:
use matcher.find() which returns true if a match could be found.
prepend \d{2} to your regex and still use matcher.matches(): Demo

VBScript RegEx - match between words

I'm having a hard time coming up with a working RegEx that words in VBScript. I'm trying to match all text between 2 keywords:
(?<=key)(.*)(?=Id)
This throws a RegEx error in VBScript. Id
Blob I'm matching against:
\"key\":[\"food\",\"real\",\"versus\",\"giant\",\"giant gummy\",\"diy candy\",\"candy\",\"gummy worm\",\"pizza\",\"fries\",\"spooky diy science\",\"spooky\",\"trapped\"],\"Id\"
Ideally, I'd end up with a comma delimited list like this:
food,real,versus,giant,giant gummy,diy candy,candy,gummy worm,pizza,fries,spooky diy science,spooky,trapped
but, I'd settle for all text between 2 keywords working in VBScript.
Thanks in advance!
VBScript's regular expression engine doesn't support lookbehind assertions, so you'll want to do something like this instead:
s = "\""key\"":[\""food\"",\""real\"",\""trapped\""],\""Id\"""
'remove backslashes and double quotes from string
s1 = Replace(s, "\", "")
s1 = Replace(s1, Chr(34), "")
Set re = New RegExp
re.Pattern = "key:\[(.*?)\],Id"
For Each m In re.Execute(s1)
list = m.Submatches(0)
Next
WScript.Echo list

scala regex pattern giving matcherror

I have a string
val path = "/bigdatahdfs/datalake/raw/lum/creditriskreporting/iffcollateral/year=2017/month=05/approach=firb/basel=3/version_partition=8/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"
the pattern
.*version_partition=(\d+)(.*)
is working as expected in regex101.com.
Requirement is to extract two strings. one is "8" (exactly after version_partition=)and another is "/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"
In scala REPL the same pattern is giving scala.MatchError. I am new in using regular expressions. Not sure what I am doing wrong here. Please help me here.
scala code is
val P = """.*version_partition=(\d+)(.*)""".r
val P(ver,fileName) = path;
I have tried with /g and /m flag also. It didn't work.
Your code works : https://scalafiddle.io/sf/Xz1Y0Ze/0
You don't need /g and /m flag.
/g ==> Perform a global match (find all matches rather than stopping
after the first match)
/m ==> Perform multiline matching
code :
val path = "/bigdatahdfs/datalake/raw/lum/creditriskreporting/iffcollateral/year=2017/month=05/approach=firb/basel=3/version_partition=8/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"
val P = """.*version_partition=(\d+)(.*)""".r
val P(ver,fileName) = path;
println(ver)
println(fileName)
Try it using a match like this:
val path = "/bigdatahdfs/datalake/raw/lum/creditriskreporting/iffcollateral/year=2017/month=05/approach=firb/basel=3/version_partition=8/vFirbtestCollateralBaselIIIData_201705_8_20170620.txt.gz"
val P = """.*version_partition=(\d+)(.*)""".r
path match {
case P(a,b) ⇒
println(a)
println(b)
}
Test
You accidentally added a white space at the end.
https://regex101.com/r/FLkZEu/2
The .* at the beginning of the regex is useless

Groovy Regular matching everything between quotes

I have this regex
regex = ~/\"([^"]*)\"/
so Im looking for all text between quotes
now i have the following string
options = 'a:2:{s:10:"Print Type";s:8:"New Book";s:8:"Template";s:9:"See Notes";}'
however doing
regex.matcher(options).matches() => false
should this not be true, and shouldn't I have 4 groups
The matcher() method tries to match the entire string with the regex which fails.
See this tutorial for more info.
I don't know Groovy, but it looks like the following should work:
def mymatch = 'a:2:{s:10:"Print Type";s:8:"New Book";s:8:"Template";s:9:"See Notes";}' =~ /"([^"]*)"/
Now mymatch.each { println it[1] } should print all the matches.