dongqiang4986 2018-04-26 17:01
浏览 49

PHP正则表达式使用Dot Net Regex作为字符串中的日期模式mm / dd / yyyy

I wanted to extract the date pattern "mm/dd/yyyy" from a string, for example, given the string:

"The quick brown fox on 4/26/2018 decided to jump over the moon"

I wanted to extract this date pattern from any string in C#. In starting out I used:

https://regex101.com/r/yG2zN1/1

Using the pcre (PHP) flavor I came up with the following and it seemed to work well for this date format in any sentence:

\d{1,2}\/\d{1,2}\/\d{4}\b

However when I put this in my C# code it would not work:

        Regex rx = new Regex(@"\d{1,2}\/\d{1,2}\/\d{4}\b");
        MatchCollection mc = rx.Matches(myTestString);  //get mm/dd/yyyy
        string date = mc[0].Value;

mc comes out false? No match?

So I went over to a couple Dot NET Regex test sites and tried http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

\d{1,2}\/\d{1,2}\/\d{4}\b - it fails on those sites also for my test string above.

My question is why does "\d{1,2}\/\d{1,2}\/\d{4}\b" work on the PHP regex to extract the date of format mm/dd/yyyy from any string but it does not work with C# regex as shown above?

  • 写回答

1条回答 默认 最新

  • douyin7416 2018-04-26 17:55
    关注

    Just wanted to clarify that for the date pattern mm/dd/yyyy in a string the regex pattern -

    @"\d{1,2}/\d{1,2}/\d{4}\b"

    does work in both Dot NET C# and at https://regex101.com/r/yG2zN1/1. What I was doing wrong at https://regex101.com/r/yG2zN1/1 was I was not putting the "@" before the regex string this made it so that I had to use the escape char . Thanks to Wiktor Stribizew I was able to go back and revisit this.

    In addition in my C# code I had a test string that was bad it was a copy and past string and must have had some weird control characters in it and that was the reason that regex pattern @"\d{1,2}/\d{1,2}/\d{4}\b" was not working. I went back to my code and deleted the original test string and retyped it and now @"\d{1,2}/\d{1,2}/\d{4}\b" works to extract the date pattern mm/dd/yyyy from any string it is embedded in. Again I have to give credit and thanks to Wiktor Stribizew for his help on solving this issue.

    Note: my string was coming from the windows 7 embedded system event log ID 6008 event.message for some reason there is some type of invisible characters / non printable characters in that string ultimately I had to use the following regex on the string to clean it: cleanString = Regex.Replace(message, @"\p{C}+", string.Empty);

    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发