Javascript正则表达式:匹配任何东西直到某些东西(如果它存在) [英] Javascript regular expression: match anything up until something (if there it exists)
问题描述
您好我是正则表达式的新手,这可能是一个非常简单的问题(希望如此)。
Hi I am new to regular expression and this may be a very easy question (hopefully).
我正在尝试使用一种解决方案来处理3种字符串
I am trying to use one solution for 3 kind of string
- 45%,预期结果:45
- 45,预期结果: 45
- ,预期结果:
我在尝试什么(让字符串为str):
What I am trying (let the string be str):
str.match(/(.*)(?!%*)/i)[1]
这在我脑海中听起来像是匹配任何事物的任何实例直到'%'如果它被发现,或者只是匹配任何东西
This in my head would sound like "match any instance of anything up until '%' if it is found, or else just match anything"
在萤火虫的头脑中,它似乎听起来更像是只是匹配任何东西而完全无视负面的前瞻。也是为了让它变得懒惰 - (。*)?
- 似乎没有帮助。
In firebug's head it seems to sound more like "just match anything and completely disregard the negative lookahead". Also to make it lazy - (.*)?
- doesn't seem to help.
让我们忘了一秒钟,在这种特殊情况下,我只匹配数字,所以 / \d * /
会这样做。我试图了解一般规则,以便我可以随时申请。
Let's forget for a second that in this specific situation I am only matching numbers, so a /\d*/
would do. I am trying to understand a general rule so that I can apply it whenever.
任何人都会非常友好地帮助我吗?
Anybody would be so kind to help me out?
推荐答案
如何更简单
str.match(/[^%]*/i)[0]
这意味着匹配零个或多个字符,这不是%
。
Which means, match zero-or-more character, which is not a %
.
编辑:如果需要解析直到< / a>
,然后你可以解析pf字符的序列,后跟< / a>
,然后丢弃< / a>
,这意味着你应该使用正面预测而不是负面。
If need to parse until </a>
, then you could parse a sequence pf characters, followed by </a>
, then then discard the </a>
, which means you should use positive look-ahead instead of negative.
str.match(/.*?(?=<\/a>|$)/i)[0]
这意味着:懒惰地匹配零个或多个字符,直到达到< / a>
或字符串结尾。
This means: match zero-or-more character lazily, until reaching a </a>
or end of string.
请注意 *?
是单个运算符,(。*)?
与不同。*?
。
Note that *?
is a single operator, (.*)?
is not the same as .*?
.
(和不用单个正则表达式解析HTML 。)
这篇关于Javascript正则表达式:匹配任何东西直到某些东西(如果它存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!