1

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.

7
  • Will this work for you? ^\s*(?:List\s*<)?\w+>?\s*\K\w+(?=\s*=|\s*;) Commented Aug 9, 2018 at 6:26
  • i replaced List in regex with any word , as it can be any class varaible .. ^\s*(?:\w*\s*<)?\w+>?\s*\K\w+(?=\s*=|\s*;) but can you please explain the regex also , what is the \K Commented Aug 9, 2018 at 6:52
  • sure, i'll add it as an answer Commented Aug 9, 2018 at 6:55
  • In which environment or language you are going to use this regex? Commented Aug 9, 2018 at 7:03
  • @Julio also i just tried with java pattern , i think \K is not supported by java compiler.<br> regexplanet.com/share/index.html?share=yyyyy3ujp0r<br> also above regex is not matching private final String COMMENTS = "test"; Commented Aug 9, 2018 at 7:06

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

its not matching variable: private final String COMMENTS = "test";
Glad to hear. You may mark the answer as 'Accepted' if it worked for you.
@Julio thanks for the answer. Your explanation doesn't match the updated pattern, can you please update it? particularly around (?:<\w+>)?
@Kartik Done! Thank you
Thanks @Julio, upvoted. If you can modify it to make it work for generics, that would be awesome! private List<String> test;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.