【问题标题】:Checking for whitespaces with RegEx使用 RegEx 检查空格
【发布时间】:2021-05-21 18:32:27
【问题描述】:

我的字符串看起来像 some text - other text,我需要删除之前的所有内容,包括连字符 - 和之后的空格

但请注意我可能有的错别字: some text -other textsome text- other textsome text-other text 或双空格而不是单空格

我正在使用 RegEx ^.*\s+\-\s+,这适用于 some text - other text- 之前和之后的单个或多个空格

但是对于缺少空格的其他可能性,我使用了两个or,所以我有^.*\s+\-\s+|.*\-\s|.*\-

有没有更简洁的模式不为此使用多个ors?

感谢您对此的任何帮助

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

【问题讨论】:

    标签: regex


    【解决方案1】:

    您可以使用一个模式来匹配除 - 之外的所有模式,而不是使用 3 个模式的交替,然后匹配 - 和可选的空白字符。

    ^[^-]*-\s*
    

    Regex demo

    如果后面应该有一个非空白字符,并且支持前瞻:

    ^[^-]*-\s*(?=\S)
    
    • ^ 字符串开始
    • [^-]*- 匹配除- 之外的任何字符0+ 次,然后匹配-
    • \s* 匹配可选的空白字符
    • (?=\S) 正向前瞻,在右边断言一个非空白字符

    Regex demo

    注意\s 和取反字符类[^-] 也可以匹配换行符。

    【讨论】:

    • 你为什么不用转义 - ?为什么不是^[^-]*\-\s*(?=\S)
    • @xyz333 因为- 不是元字符,所以您不必转义它。只有当你把它放在一个字符类中并且它不是第一个或最后一个字符时,你必须将它转义以防止意外匹配一个范围。
    【解决方案2】:

    第一种解决方案:使用您展示的示例,请尝试以下操作。

    ^.*?\s+\S+\s?-\s*(.*)$
    

    ^.*?\s+\S+\s*-\s*(.*)$
    

    Online demo for above regex



    第二个解决方案:您也可以使用 \K 选项来忘记匹配的正则表达式部分,在这种情况下尝试:

    ^.*?\s+\S+\s?-\s*\K.*$
    

    ^.*?\s+\S+\s*-\s*\K.*$
    

    Online demo for above regex

    第一种解决方案说明:

    ^.*?\s+  ##From starting of value matching till 1st occurrence of space(s).
    \S+\s?   ##Matching 1 or more non-space occurrences followed by optional space here.
    -\s*     ##Matching - followed by optional space.
    (.*)$    ##Matching everything till last of value.
    

    第二个解决方案说明:

    ^.*?\s+  ##Matching everything till 1st space occurrence(s) from starting of value.
    \S+\s?   ##Matching non spaces 1 or more occurrences followed by space optional.
    -\s*\K   ##Matching - followed by spaces(0 or more occurrences) and \K will discard all previous matched values(so that we can match exact values as per output).
    .*$      ##Matching everything after previously matched values(which is discarded by \K).
    

    【讨论】:

    • 谢谢,我会研究这个提高自己的能力
    猜你喜欢
    • 1970-01-01
    • 2013-03-13
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多