如何进行“打印"?语句以打印多个字符串Javascript? [英] How to make "print" statement to print multiple strings Javascript?

查看:250
本文介绍了如何进行“打印"?语句以打印多个字符串Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为打印语句做一个小型解释器.这是我到目前为止所做的演示: 演示

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:

  • 打印我的书" +是" +"xx"
  • 打印一个(其中a是可变名称)
  • 打印一个+是我的电话号码"

到目前为止,我一直在尝试一些东西并构建一些东西,但是我有两个问题:

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

  1. 首先,我尝试构建一个新的打印正则表达式:

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

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

因此这将与print语句匹配,第一个参数可以是string(")或变量名.然后,我尝试使用(.*)捕获所有其他变量或字符串,并在以后使用它们. (我想建立一个while循环). 但是我的问题是,当我进行匹配时,它会输出一个空值.因此,当我制作alert(t)时,t[2]的值是empty(,,).

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. 第二个问题是我无法测试print的第一个参数是变量还是字符串.我尝试了这个: t1 = t[1].match(rxString);但它输出null(因为实际上它搜索"",但是当保存在(t)中时,它们将从字符串中删除)
  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)

这是我的演示

请您能帮我解决这个问题吗?预先感谢

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

推荐答案

仅使用正则表达式构建解释器是困难的,也是不可能的.您可能宁愿将输入标记化(例如,在空格处分隔+一些选定的特殊字符之前/之后),然后分别检测和处理每个标记.

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.

如果您想变得更复杂,那么当然应该为您的语言定义一种语法,并使用@ peter-schneider指出的类似PEG.js之类的库进行匹配.

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] == '\'') { /* ... */ }

这篇关于如何进行“打印"?语句以打印多个字符串Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆