【问题标题】:Conditional Pattern条件模式
【发布时间】:2014-02-14 20:47:46
【问题描述】:

我有这段文字:

<pre id="lyricsText">
__Verse 1
At the starting of the week
At summit talks, you'll hear them speak
It's only Monday

Negotiations breaking down
See those leaders start to frown
It's sword and gun day

__Chorus 1
Tomorrow never comes until it's too late

__Verse 2
You could be sitting taking lunch
The news will hit you like a punch
It's only Tuesday

You never thought we'd go to war
After all the things we saw
It's April Fools' day

__Chorus 1 (R:2)
Tomorrow never comes until it's too late

__Verse 3
You hear a whistling overhead
Are you alive or are you dead?
It's only Thursday

You feel a shaking on the ground
A billion candles burn around
Is it your birthday?

__Chorus 1 (R:2)
Tomorrow never comes until it's too late

__Outro
Make tomorrow come, I think it's too late
</pre>

我正在尝试捕获标题。为此,我使用这种模式:

var headers = /__.*/g;

效果很好,但我想排除 (R:2) 或任何类似的东西。我正在使用另一种模式来捕获和修改(R:x) 部分:

/(\(R.{0,2}\))/g

我找不到让它们一起工作的方法。

如何编写捕获/__.*/ 以及如果存在排除/\(R.{0,2}\)/

FIDDLE

【问题讨论】:

  • 那么对于__Chorus 1 (R:2),您想捕获__Chorus 1
  • 是的,这就是我想要做的。

标签: javascript regex


【解决方案1】:

假设对于__Chorus 1 (R:2),您希望匹配__Chorus 1,这样就可以了:

/__(.(?!\(R.{0,2}\)))*/g;

匹配尽可能多的字符,直到下一个序列为(R.{2})

你的小提琴输出:

["__Verse 1", "__Chorus 1", "__Verse 2", "__Chorus 1", "__Verse 3", "__Chorus 1", "__Outro"] 

【讨论】:

    【解决方案2】:
    var headers = /__[A-Za-z0-9 ]*(?=\(R:\d\))?/g;
    

    JS 小提琴: http://jsfiddle.net/gjmf4/3/

    【讨论】:

    • 不知道为什么我的回答得到了如此多的关注。我开始时几乎完全一样,除了没有最后的?,意识到它匹配标题与(R..),所以完全改变了方法 - 忘记了?之后的事实前瞻会修复它..
    • @OGHaza 好吧,可能导致这种情况的原因是您不能在环顾四周放置量词。
    • @Jerry 通过量词你指的是??我不是一个正则表达式天才,这实际上是我希望做的,把一些有用的东西放在那里并获得一些反馈。
    • @KevinBowersox 是的,? 确实是一个量词,就像 +*{1,2}。我自己刚刚看到了这个问题,但是如果你想把?放在一个前瞻上,你需要先把它分组,像这样:(?:(?=\(R:\d\)))?
    • @Jerry 那我的小提琴为什么有用?我注意到这个表达式在 RegExr 中不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多