【问题标题】:how to tokenize/parse string literals from javascript source code如何从 javascript 源代码中标记/解析字符串文字
【发布时间】:2009-03-24 06:05:27
【问题描述】:

我正在使用 C# 编写一个程序,该程序需要加载一些 JavaScript 代码,对其进行解析并对代码中的 字符串文字 进行一些处理(例如用其他内容覆盖它们)。

我的问题是,我很难设计一种优雅的方式来真正在 JavaScript 代码中找到字符串文字。

例如,看看下面的示例 JavaScript 代码。您是否看到即使 Stack Overflow 的代码高亮显示器也能够在代码中挑选出字符串文字并将它们变成红色?

我想基本上做同样的事情,除了我不会把它们变成不同的颜色,但我会对它们做一些处理,并可能用完全不同的字符串文字替换它。

var dp = {
    sh :                    // dp.sh
    {
        Utils   : {},       // dp.sh.Utils
        Brushes : {},       // dp.sh.Brushes
        Strings : {},
        Version : '1.3.0'
    }
};

dp.sh.Strings = {
    AboutDialog : '<html><head><title>About...</title></head><body class="dp-about"><table cellspacing="0"><tr><td class="copy"><p class="title">dp.SyntaxHighlighter</div><div class="para">Version: {V}</p><p><a href="http://www.dreamprojections.com/syntaxhighlighter/?ref=about" target="_blank">http://www.dreamprojections.com/SyntaxHighlighter</a></p>&copy;2004-2005 Alex Gorbatchev. All right reserved.</td></tr><tr><td class="footer"><input type="button" class="close" value="OK" onClick="window.close()"/></td></tr></table></body></html>',
    
    // tools
    ExpandCode : '+ expand code',
    ViewPlain : 'view plain',
    Print : 'print',
    CopyToClipboard : 'copy to clipboard',
    About : '?',
    
    CopiedToClipboard : 'The code is in your clipboard now.'
};

dp.test1 = 'some test blah blah blah' +  someFunction()  + 'asdfasdfsdf';
dp.test2 = 'some test blah blah blah' +  'xxxxx'  + 'asdfasdfsdf';
dp.test3 = 'some test blah blah blah' +  "XXXXsdf "" \" \' ' sdfdff "" \" \' ' asdfASDaSD FASDF SDF'  + 'asdfasdfsdf";

dp.SyntaxHighlighter = dp.sh;

我尝试通过查找引号进行解析,但是当字符串文字中有转义字符时,它会变得复杂。我正在考虑的另一个解决方案是使用正则表达式,但我对正则表达式不够强大,我什至不确定这是否是我应该细读的途径。

我想看看 Stack Overflow 是怎么想的。非常感谢!

【问题讨论】:

    标签: c# javascript parsing


    【解决方案1】:

    Regexs in Depth: Advanced Quoted String Matching 有一些很好的例子来说明如何使用正则表达式来做到这一点。

    其中一种方法是:

    (["'])(?:(?!\1)[^\\]|\\.)*\1

    你可以这样使用它:

    string modifiedJavascriptText =
       Regex.Replace
       (
          javascriptText, 
          @"([""'])(?:(?!\1)[^\\]|\\.)*\1", // Note the escaped quote
          new MatchEvaluator
          (
             delegate(Match m) 
             { 
                return m.Value.ToUpper(); 
             }
          )
       );
    

    在这种情况下,所有的字符串文字都是大写的。

    【讨论】:

      猜你喜欢
      • 2013-04-07
      • 2016-01-19
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多