[英]Evaluating a regular expression range
是否有一種很好的方法來評估正則表達式范圍,例如對於諸如
http://example.com/[a-z]/[0-9].htm
這將被轉換為:
http://example.com/a/0.htm
http://example.com/a/1.htm
http://example.com/a/2.htm
...
http://example.com/a/9.htm
...
http://example.com/z/0.htm
http://example.com/z/1.htm
http://example.com/z/2.htm
...
http://example.com/z/9.htm
我一直在為此撓頭,如果沒有字母和數字循環的話,就沒有很好的方法。
提前致謝!
我想一般來說沒有辦法擴展正則表達式。 你的例子
http://foo.com/[a-z]/[0-9].htm
是一個非常簡單的正則表達式,例如沒有*
或+
。 您將如何擴展這樣的正則表達式?
在您的情況下,您可能會遇到一些循環,但是正如我所說的-這是不典型的 (簡單)正則表達式。
如果您確實需要執行此操作,則使用遞歸生成字符串並不難。 以下是在Java中執行此操作的代碼段:
public class Explode {
static void dfs(String prefix, String suffix) {
final int k = suffix.indexOf('[');
if (k == -1) {
System.out.println(prefix + suffix);
} else {
prefix += suffix.substring(0, k);
char from = suffix.charAt(k+1);
char to = suffix.charAt(k+3);
suffix = suffix.substring(k+5);
for (char ch = from; ch <= to; ch++) {
dfs(prefix + ch, suffix);
}
}
}
public static void main(String[] args) {
String template = "http://example.com/[a-c]/[0-2][x-z].htm";
dfs("", template);
}
}
( 請參閱完整輸出 )
這是一個標准的遞歸元組生成器,但之間有一些字符串插入。 移植到C#很簡單。 您想要使用可變的StringBuilder
類,以獲得更好的性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.