2014-05-05 165 views
0

如何从这些给定的url字符串中提取?正则表达式从URL获得ID

my-domain/product/name-product-ID123.html 
my-domain/product/name-product-ID123.html/ 
my-domain/product/name-product-ID123.html?bla=123&some=456 

如果不ID,等于2 (AB, EF, GH, ...)

有人可以帮我长的随机字符串?

回答

0

$zeichenkette = "my-domain/product/name-product-ID123.html"; $suchmuster = '/ID[0-9]{3}/'; preg_match($suchmuster, $zeichenkette, $treffer, PREG_OFFSET_CAPTURE, 3); print_r($treffer);

应打印ID123。

0

试试这个:

(?<=product-)ID[0-9]+(?=\.html) 
  • (?<=product-)正回顾后 - 断言,ID由字符串product-

  • ID前面匹配的人物ID字面上

  • [0-9]+匹配数字序列

  • (?=\.html)积极前瞻 - 断言,ID后跟.html

2

这可能不是一个工作,正则表达式,但对于您所选择的语言现有的工具。正则表达式不是一个魔术棒,你在涉及字符串的每一个问题上都会挥手致意。您可能想要使用已经编写,测试和调试的现有代码。

在PHP中,使用parse_url函数。

Perl:URI module

红宝石:URI module

。NET:'Uri' class

+0

+1当谈到URI时,我更喜欢使用Regex解析的URI解析。 – MxyL

0

短而有效:

<?php 
$links = <<< LOB 
my-domain/product/name-product-ID123.html 
my-domain/product/name-product-ID123.html/ 
my-domain/product/name-product-ID123.html?bla=123&some=456 
LOB; 

preg_match_all('/-(ID\d+)\./',$links ,$ids, PREG_PATTERN_ORDER); 
for ($i = 0; $i < count($ids[1]); $i++) { 
    echo $ids[1][$i]."\n"; 
} 
/* 
ID123 
ID123 
ID123 
*/ 
?> 

现场演示:
http://ideone.com/OqhL6b

说明:

Match the character “-” literally «-» 
Match the regular expression below and capture its match into backreference number 1 «(ID\d+)» 
    Match the characters “ID” literally «ID» 
    Match a single digit 0..9 «\d+» 
     Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
Match the character “.” literally «\.»