2

意思是,我想匹配:

$10

或者

$

但不是这个:

${name}

或者:

$image{http://wrfgadgadga.com/gadgad.png}

我还想匹配其他所有内容……普通字符、符号、数字等。

匹配除以 $ 开头的所有内容之外的所有内容都很容易。就像这样:

def literalCharacter: Parser[String] = """[^\$]""".r

我已经尝试过使用 (?!i) 或 (?!{) 多种组合的正则表达式前瞻语法,但我似乎无法让它工作。我也试过用 = 而不是 ! 像这样: (?=i)

基本上,我已经尝试以我可以用 [^\$] 表达式成像的各种方式注入这些前瞻,但我无法让它工作。

帮助?

编辑:Hrm,这似乎有效:

[^\$]|\$(?!i)|\$(?!\{)
4

1 回答 1

3

您的将无法正确匹配字符串x$。如果要匹配整个字符串,请尝试

"""^\$$|^[^\$].*$|^\$[^i\{].*$"""

我们匹配由 分隔的三个序列中的任何一个|

^\$$
^[^\$]+.*$
^\$[^i\{]+.*$

让我们把它分开:

// First pattern--match lone '$' character
^   // Matches start of string
\$  // Matches the literal character '$'
$   // Matches end of string

// Second pattern--match a string starting with a character other than '$'
^       // Start of string
[^\$]+  // Match at least one non-'$':    
           +   // Match one or more
      [^  ]    // ...of characters NOT listed...
        \$     // ...namely, a literal '$'
.*      // Any number of other characters
$       // End of the string

// Third pattern--match a string starting with '$' but not '$i' or '${'
^        // Start of string
\$       // The literal character '$'
[^i\{]+  // Match at least one non-'i'/non-'{'
.*       // Any number of other characters
$        // End of the string

如果您不匹配整个字符串,则必须担心诸如foo$image{Hi}. 如果您还想匹配空字符串,^$|请在匹配之前添加。

请注意,这是专门为使用正则表达式而编写的,而不是考虑到您的解析器组合器。根据您拥有的其他规则,您可能想要也可能不想匹配整个字符串。

于 2010-10-24T17:15:24.250 回答