Intellij provides regex "assistance" (syntax checking) for parameters that expect regular expressions, eg coding:
String[] array = string.split("(*.");
will mark an error under the regex and provide a tool tip error:
Unclosed group
This also works for variables, eg
String myVar = "(*."; // shows above error here
String[] array = string.split(myVar);
But if I create my own method that expects a regex, I don't get this assistance, eg:
String[] myMethod(String regexParameter) {
return someString.split(regexParameter);
}
myMethod("(*."); // no "error" marker like above
Although Intellij can figure out regexParameter
should be a valid regex, it doesn't check it like it does for JDK parameters.
How do I get regex assistance for my own method parameters?
Ideally there would be an annotation-based solution or similar, where the method's parameters are "defined" to Intellij as being regex, so all developers automatically get the assistance when they load up the code base.
To activate regex language for a parameter in your IDE, double-click on the regex string and press AltEnter (shortcut for Intention Actions) and choose "Inject Language or Reference", then choose "Regexp" in the resulting list:
This will permanently attach regex to the parameter at all call sites.
To do this to multiple text fragments, hold down ShiftAlt keys and keep double-clicking all the instances (the multi-select feature in IntelliJ).
To create a parameter that automatically has Intellij's language assist feature, so your other dev team members can automatically get regex assistance too, use IntelliJ's IntelliLang plugin by adding jetbrains' annotations library as a compile dependency, eg for gradle:
dependencies {
...
compile 'org.jetbrains:annotations:15.0'
}
Then to use it, specify "RegExp"
as the @Language
for the parameter:
import org.intellij.lang.annotations.Language;
void myMethod(@Language("RegExp") String regex) {
// some impl
}
Regex validation of Strings passed to the method will now work from any method invocation by anyone editing the source code in Intellij.
Note: There's an alternative, which is not recommended, to adding a dependency to your build (if you have one), and knowing that the effect is only within your IDE and you'll have to compile within your IDE, Intellij lets you do this:
@Language("RegExp")
annotation to the method parameterIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With