How to make “print” statement to print multiple strings Javascript?

∥☆過路亽.° 提交于 2019-12-12 03:35:11

问题


I am trying to make a small interpreter for print statement. Here is a demo of what I have done till now: DEMO

What I want to reach now is to print multiple string connected with +like:

  • print "My book" + "is" + "xx"
  • print a (where a is varible name)
  • print a + "is my number"

I have tried something till now and build something but I have two problems:

  1. First I tried to build a new print regexp:

    /^ *print +(?:"([^"]*)"|([a-zA-Z]\w*)) *(.*)$/

so this will match the print statement, the first argument could be a string("") or a variable name. And then with (.*) I am trying to catch all other variables or strings and to use them later. ( I have in mind to build a while loop). But my problem is that when I make the match it outputs me an empty value. So when I make alert(t) the t[2] value is empty(,,).

  1. The second problem is that I am not able to test if the first parameter of print is a varible or a string. I tried this: t1 = t[1].match(rxString); but it output null ( because in fact it search for "", but when saved in (t) they are removed from the string)

Here is my DEMO

Please can you help me how to solve this this? Thanks in advance


回答1:


Building interpreters with only regexes is between difficult and impossible. You might rather tokenize your input (e.g. split at white spaces + before/after some selected special characters) and then detect and handle each token individually.

If you want to go more complex you should of course define a grammar for your language and match that using a library like PEG.js as @peter-schneider pointed out.

You should be able to detect string literals quite easily by whether the token starts with a " or ':

if (token[0] == '"' || token[1] == '\'') { /* ... */ }


来源:https://stackoverflow.com/questions/30006376/how-to-make-print-statement-to-print-multiple-strings-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!