3

これらのURLを考えると:

1: http://site/page-name-one-123/
2: http://site/page-name-set2/
3: http://site/set20

私は最後のURLセグメントに適用されるこの式を書きました:

(?(?<=set[\d])([\d]+)|([^/]+))

私がやりたいのは、URLセグメントが「set」で始まり、直後の数字である場合にのみ、すべての数字の後に「set」が続くことです。それ以外の場合は、セグメント全体(スラッシュを除く)を使用します。

この正規表現を書いたので、「/」以外の文字と一致します。テストステートメントで何か間違ったことをしていると思います。誰かが私を正しく指摘できますか?

ありがとう

更新Joshの入力 のおかげで、少し遊んでみたところ、これが私のニーズにより適していることがわかりました。

set-(?P<number>[0-9]+)|(?P<segment>[^/]+)
4

2 に答える 2

1

このパターンがお役に立てば幸いです。お客様の要件に基づいてまとめました。必要なセグメントのみを取得するように、一部のグループをキャプチャしないように設定してみることをお勧めします。ただし、最初に設定せずに設定たURLを個別にキャプチャします。

((?<=/{1})(((?<!set)[\w|-]*?)(\d+(?=/?))|((?:set)\d+)))

必要に応じて、 RegExrを使用して分解することをお勧めします。

于 2012-04-22T10:12:46.407 に答える
0

これを試して:

((?<=/)set\d+|(?<=/)[^/]+?set\d+)

説明

<!--
Options: ^ and $ match at line breaks

Match the regular expression below and capture its match into backreference number 1 «((?<=/)set\d+|(?<=/)[^/]+?set\d+)»
   Match either the regular expression below (attempting the next alternative only if this one fails) «(?<=/)set\d+»
      Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=/)»
         Match the character “/” literally «/»
      Match the characters “set” literally «set»
      Match a single digit 0..9 «\d+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Or match regular expression number 2 below (the entire group fails if this one fails to match) «(?<=/)[^/]+?set\d+»
      Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) «(?<=/)»
         Match the character “/” literally «/»
      Match any character that is NOT a “/” «[^/]+?»
         Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
      Match the characters “set” literally «set»
      Match a single digit 0..9 «\d+»
         Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
-->
于 2012-04-22T10:39:32.057 に答える