-4
$string = "hello/welcome";

i want "welcome" only.

$string = "hello-welcome-to-the-world";

i want "hello-welcome"

i try this

print $1 if($string =~ m#(?:/|)(.*)(?:-to-)#);  # got hello-welcome
print $1 if($string =~ m#(?:/)(.*)(?:-to-|)#);  # got welcome

but i cant able to get the required output from single regexp . please solve and explain ...

by using this (?:\w.+/)?(.*?(?=$|-to-)) , i got the answer for both strings

4

2 に答える 2

1

この正規表現は、両方のケースに一致します。目的の出力も にあり$1ます。

((?:\w+-)?welcome)

(?:\w+-)?オプションで、ウェルカムの前にハイフンが続く単語に一致します。オプションで一致するため、そこにない場合、出力は単に「歓迎」されます。

于 2012-06-01T12:36:08.417 に答える
0
(?<=^|/).*?(?=$|-to-)

これは、(文字列の開始またはスラッシュ)と(文字列の終了または-to-)の間の最短の一致と一致します。

これは、ルックアラウンドを使用する場合に、キャプチャグループを抽出する必要がない多くのケースのもう1つです。

編集:可変長後読みは機能しないので、これを試してください:

(?<![^/])[^/]*?(?=$|-to-)
于 2012-06-01T12:41:44.000 に答える