Sandeep Chauhan
Sandeep Chauhan

Reputation: 171

RegEx for java variable

I want to capture the java variable name in java file using regex. i am able to achieve one level where variable is assigned something , but if variable is not assigned anything then how to get it ?

My Regex : (\w*)<?>?\s*=(?=(?:[^"]|"[^"]*["])*$)
Click here for sample it should included both variable but not import class;

import java.io.File;
import java.io.IOException ;
String test="test";
String test22;
String includeThisAlso ;

it should match the variable but not import class.

Upvotes: 1

Views: 95

Answers (1)

Julio
Julio

Reputation: 5308

Try with this:

^\s*\w+(?:\s+\w+)*?(?:\s*<\w+>)?\s+(\w+)(?=\s*[=;])

Demo

Explained:

^ \s*              # Line starts with one or more spaces
  \w+              # a word (1 or more letters, numbers and '_')
  (?:\s+\w+)*?     # several extra words, separated by spaces. Ungreedy
  (?:\s*<\w+>)?    # Optional '<' + Word '>'
  \s+(\w+)         # Capture the variable with a group ()
  (?=\s*[=;])      # It must be followed by spaces and then '=' or ';'

Later on, you just need to reference the first capturing group. that will have the name of the variable

Editted to allow matching generics.

Upvotes: 1

Related Questions