【问题标题】:Help with regex pattern帮助正则表达式模式
【发布时间】:2009-04-01 00:31:52
【问题描述】:

我有一个txt文件,每一行都有一组随机字符串,我只需要选择只包含字符的行:1234567890qwertyuiopasdfghjklzxcvbnm-._~

我正在逐行阅读并逐字符验证,我认为这不是最好的方法,而且我认为 RegEx 会是完美的。

那么任何人都可以为此提供模式吗?

谢谢!

【问题讨论】:

    标签: c# regex


    【解决方案1】:
     /^[-0-9a-z._~]*$/
    
     ^       :: matches the start of a string/start of a line
     [       :: start of a character class, means match any one of the contained characters
     -       :: dash has a special meaning in character classes, so to avoid having it interpreted for its special meaning, list it first
     0-9     :: shorthand for 0123456789 in a character class
     a-z     :: shorthand for abcdefghijklmnopqrstuvwxyz in a character class
     ._~     :: means exactly these characters in a character class
     ]       :: end of the character class 
     *       :: match zero or more of the previous atom (in this case, the character class)
     $       :: matches the end of a string/end of a line
    

    【讨论】:

      【解决方案2】:

      如果我理解你的话,你可以这样做:

      /^([-0-9a-zA-Z._~]\n)+$/
      

      不区分大小写,检查行尾且不匹配空行。

      【讨论】:

      • 如果他正在逐行处理数据,则不应该有任何换行符。此外,您的正则表达式将匹配一个空行; OP 对此没有说什么,但我会使用 '+' 而不是 '*' 作为第一切。
      【解决方案3】:

      不难发现正则表达式应该等同于^[1234567890qwertyuiopasdfghjklzxcvbnm\-._~]*$。从那里你可以缩小范围,用0-9、a-z等代替。在使用从别人那里得到的答案之前,您应该学习正则表达式的基础知识。

      【讨论】:

        猜你喜欢
        • 2011-05-11
        • 1970-01-01
        • 2011-06-10
        相关资源
        最近更新 更多