条件模式

时间:2014-02-14 20:47:46

标签: javascript regex

我有这样的文字:

<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

2 个答案:

答案 0 :(得分:4)

假设__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"] 

答案 1 :(得分:2)

var headers = /__[A-Za-z0-9 ]*(?=\(R:\d\))?/g;

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