Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one automatically get Intellij's regex assistance for one's own regex parameters

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?


Note:

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.

like image 300
Bohemian Avatar asked May 03 '16 16:05

Bohemian


1 Answers

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:

enter image description here

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:

  1. Add @Language("RegExp") annotation to the method parameter
  2. Click on the red bulb icon to import annotations into the classpath

enter image description here

enter image description here

like image 134
Bajal Avatar answered Oct 05 '22 17:10

Bajal