In Ruby, if I have two Regexps, I have the possibility to create another regexp like this:
a = /\d+/ # Matches digits
b = /\s+/ # Matches whitespaces
c = Regexp.union(a, b) # Matches sequences that consist only of digits or only of whitespaces
I want to do the same thing in Scala, but I didn’t find out how I could do that. Note that I am not asking for a syntax to create a union of character classes like (\d+)|(\s+) in the previous example, I am really looking for a possibility to create a new Regexp from two given Regexps.
Actually, in the end, I will not do it for just two Regexps but a large number. I don’t care about grouping or anything, I just want to know if a String matches one of a list of given Regexps. I could just check all of them in a loop, but that is too inefficient, that is why I need one Regexp to check the union.
Scala uses the Java regex engine, which is based on the class
java.util.regex.Pattern.Patternhas exactly one method that can create a regex:That’s it, and Scala doesn’t give you any relevant enhancements.
But one thing you can do is use the built-in unioning in match statements, here shown with capturing groups in case you want to pull something out of the string:
found
found
If you really want a combined regex, you have to do it at the string level. You can get the java
Patternfrom a Scala regex with.pattern, and another.patternthen gets the string. Most regexes can be wrapped safely in(?:)to get a non-capturing block, so you can combine like so:However, any capturing groups inside will both be represented, but the non-used branch will be
null(not exactly a good way to write idiomatic Scala, but anyway, this is what Java uses):