简体   繁体   中英

Regex to match everything but the comment

Given this Java regex code for a PSQL statement, I'm having some issues trying to match everything but the comments in the statements. This is not getting the lines with the comments in them.

^(?!.*?(?:-- [a-z]*-[a-z]*: [a-zA-z]*)).*$

This is the PSQL:

CREATE TABLE "test_table" (
   "user_id" serial PRIMARY KEY,
   "username" VARCHAR (50) UNIQUE NOT NULL, -- foreign-key: t_supply_type
   "password" VARCHAR (50) NOT NULL,
   "email" VARCHAR (355) UNIQUE NOT NULL, -- foreign-key: t_supply_type
   "created_on" TIMESTAMP NOT NULL,
   "last_login" TIMESTAMP
);

What am I missing?

One simple approach for your exact data would be to just remove all occurrences of -- until the end of the line. Consider:

String line = "\"username\" VARCHAR (50) UNIQUE NOT NULL, -- foreign-key: t_supply_type";
line = line.replaceAll("\\s*--.*$", "");
System.out.println(line);

This prints:

"username" VARCHAR (50) UNIQUE NOT NULL,

Assuming you have already read the entire SQL query into a single string, the above replacement should also still work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM