如何编写一个正则表达式来匹配所有不是 '$' 的字符接下来是“i”;或'{'?
意思是,我想匹配:
$10
或,
$
但不是这个:
${name}
或:
$image{http://wrfgadgadga.com/gadgad.png}
我还想匹配其他所有内容...普通字符、符号、数字等。
匹配除以 $ 开头的内容之外的所有内容都很容易。就像这样:
def literalCharacter: Parser[String] = """[^\$]""".r
我已经尝试使用 (?!i) 或 (?!{) 的多种组合来使用正则表达式前瞻语法,但我似乎无法让它工作。我还尝试用 = 而不是 ! 重写它。像这样: (?=i)
基本上,我尝试用 [^\$] 表达式以我能想象的各种方式注入这些前瞻,但我无法让它工作。
帮助?
编辑:嗯,这似乎有效:
[^\$]|\$(?!i)|\$(?!\{)
Meaning, I want to match:
$10
or
$
but not this:
${name}
or:
$image{http://wrfgadgadga.com/gadgad.png}
I also want to match everything else... normal characters, symbols, numbers, etc.
Matching everything but things that start with $ is easy. It's like this:
def literalCharacter: Parser[String] = """[^\$]""".r
I've tried the regular expression look-ahead syntax using (?!i) or (?!{) in numerous combinations but I can't seem to get it to work. I've also tried rewriting it with the = instead of the ! like this: (?=i)
Basically, I've tried injecting these look-aheads in every way I can image with the [^\$] expression and I can't get it work.
Help?
EDIT: Hrm, this seems to work:
[^\$]|\$(?!i)|\$(?!\{)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的字符串无法正确匹配
x$
等字符串。如果你想匹配整个字符串,那么尝试我们匹配由
|
分隔的三个序列中的任何一个:让我们把它拆开:
如果你不匹配整个字符串,你必须担心像
foo$image{Hi}
这样的东西。如果您还想匹配空字符串,请在匹配项前面添加^$|
。请注意,这是专门为正则表达式而编写的,而不是考虑到您的解析器组合器。根据您拥有的其他规则,您可能希望也可能不希望匹配整个字符串。
Yours won't match strings like
x$
properly. If you want to match the entire string, then trywhere we are matching either of three sequences separated by
|
:Let's take this apart:
If you don't match the whole string, you have to worry about things like
foo$image{Hi}
. If you want to match the empty string also, prepend^$|
to the match.Note that this is written to work specifically with regexes, not with your parser combinator in mind. Depending on what other rules you have, you may or may not want to match the whole string.