0

How to write a Java regular expression for a commented SQL code like below?

/*
    SELECT * FROM Table1;
    -- Comment in comment
    Another SQL code
*/
SQL-code
-- One line comment
/**/ -- Yet one comment
/* And yet one comment */

This is my current wrong variant: (--.*)|(/\*(.*\n)*\*/).

I know that comment signatures (--, /**/) can be inside string but for my purpose we can consider so strings as comments, it doesn't matter. The most important to exclude all commented SQL code.

2
  • Is this to protect against SQL injection? Commented Nov 19, 2019 at 9:34
  • @VLAZ nope, to build diagram from procedures which tables are used inside procedure body, so I need to remove commented SQL code to analyzer didn't extract table names from comments. Commented Nov 19, 2019 at 9:38

1 Answer 1

2

Try this pattern for matching comments:

(?s)(?:\/\*.*?\*\/|--[^\n]*)

Explanation:

(?s) - single line mode, . matches newline

(?:...) - non-capturing group

\/\* - match /* literally

.*? - match zero or more of any characters (non-greedy)

\*\/ - match */ literally

| - alterantion - match pattern on the left side or on the right side of it

-- - match -- literally

[^\n]* - match zero or more characters other from newline character

Demo

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

1 Comment

Thank you, for my task it works perfectly. And special thank for explanation)

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.