简体   繁体   中英

detecting and removing single line comments in code in Java

So I am making this compiler which compiles a text file into machine code for an OS to read from an SD card. code will look something like this: (Ra text_to_store) which stores text in to string slot a. most of it seems to be doable with

mystring=mystring.replace("String ","R");
mystring=mystring.replace("=","");
mystring=mystring.replace(";","");
//cannot replace " with nothing, how do I get around this?

as this turns String a=text_t_ store; into the correct code.

but of course not all can be done with this. for example, I need to get rid of comments (//commented stuff) which is not doable with .replace, along with a few other things. this is probably something simple, but I cannot find it!

ps can you also provide a link/help with text formatting? for example int var; needs to be turned into a number for the slot of RAM. thanks in advance!

Use mystring.replaceAll which uses a regular expression, such as

mystring = mystring.replaceAll("//.*$","");

replacing from the // to the end of the line with nothing

您可以使用replaceAll和一个正则表达式将所有内容放在一行中

mystring=mystring.replaceAll("(?:.|\\s)*String ([\\w]+)=(.*?);(?:.|\\s)*","R$1 $2");

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