【问题标题】:regex where input has & char at end of string输入在字符串末尾有 & 字符的正则表达式
【发布时间】:2017-02-27 09:20:06
【问题描述】:

我正在使用这个正则表达式:

.*-p(.\d+)-fun\b含义:

.* => any char at the beginning, 
-p => static string ,
(.\d+) => number in first group,
-fun => static string ,
\b => end of string ,

我的测试:

http://example.com/abcd-p48343-fun             Matched 
http://example.com/abcd-p48343-funab           not matched
http://example.com/abcd-p48343-fun&ab=1        Matched 

为什么最后一个测试匹配?

似乎 & char 结尾的字符串将它们分成两个字符串。 http://example.com/abcd-p48343-fun&ab=1中正则表达式不匹配的解决方案是什么?

.*-p(.\d+)-fun$ 也经过测试但无法正常工作。

【问题讨论】:

  • @PawełŁukasik - OP 使用的是 .net 风味正则表达式而不是 PCRE
  • @PawełŁukasik 看看这个regexr.com/3fd4o
  • @Moslem7026 你测试的例子是错误的或者使用多行选项来表明你当时对一行感兴趣:regexr.com/3fd4r

标签: asp.net .net regex regular-language


【解决方案1】:

这个正则表达式:

.*-p(.\d+)-fun$

仅匹配第一个示例:

VB.Net 代码:

Dim Tests As New List(Of String)
Dim Pattern As String
Dim Parser As Regex

Tests.Add("http://example.com/abcd-p48343-fun")
Tests.Add("http://example.com/abcd-p48343-funab")
Tests.Add("http://example.com/abcd-p48343-fun&ab=1")

Pattern = ".*-p(.\d+)-fun\b"
Parser = New Regex(Pattern)
Console.WriteLine("Using pattern: " & Pattern)
For Each Test As String In Tests
    Console.WriteLine(Test & " : " & Parser.IsMatch(Test).ToString)
Next
Console.WriteLine()

Pattern = ".*-p(.\d+)-fun$"
Parser = New Regex(Pattern)
Console.WriteLine("Using pattern: " & Pattern)
For Each Test As String In Tests
    Console.WriteLine(Test & " : " & Parser.IsMatch(Test).ToString)
Next
Console.WriteLine()

Console.ReadKey()

控制台输出:

Using pattern: .*-p(.\d+)-fun\b
http://example.com/abcd-p48343-fun : True
http://example.com/abcd-p48343-funab : False
http://example.com/abcd-p48343-fun&ab=1 : True

Using pattern: .*-p(.\d+)-fun$
http://example.com/abcd-p48343-fun : True
http://example.com/abcd-p48343-funab : False
http://example.com/abcd-p48343-fun&ab=1 : False

【讨论】:

    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 2011-02-25
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2019-12-18
    相关资源
    最近更新 更多