【问题标题】:Regexp to match only n occurrences of a char in a string正则表达式仅匹配字符串中出现的 n 个字符
【发布时间】:2012-04-06 21:02:23
【问题描述】:

我有一个类似2005:10:29 12:23:53 的字符串,我希望只用- 替换出现的前两次:

预期结果2005-10-29 12:23:53

编辑:

我在 KDE 的 krename 工具中需要这个正则表达式,我无法编辑/格式化原始的 [exifExif.Image.DateTime] 女巫返回不需要的 2005:10:29 12:23:53 格式,但是有一个 Find and Replace 来后处理字符串

(?<=\d{4}):|:(?=\d{2}\s) 完成 on rubular 的工作,但在 KDE 中没有 :(

我相信还有更多的解决方案。

编辑:

:(?=\d{2}:\d{2}\s)|:(?=\d{2}\s) 甚至可以在 KDE 上工作

阅读后找到了这个解决方案

You can use a full-fledged regular expression inside the lookahead.
Most regular expression engines only allow literal characters and
alternation inside lookbehind, since they cannot apply regular
expression backwards.

Regex tutorial

【问题讨论】:

标签: regex kde4


【解决方案1】:

只需拨打replace()两次:

"2005:10:29 12:23:53".replace(/:/,'-').replace(/:/,'-')

【讨论】:

    【解决方案2】:

    JavaScript:

    版本 1

    str = str.split(' ')[0].replace(/\:/g,'-')+' '+str.split(' ')[1]
    

    第 2 版

    str = str.replace(/(\d{4}):(\d{2}):(\d{2})(.*)/,"$1-$2-$3 $4")
    

    DEMO

    【讨论】:

    • 对不起,我删除了混淆标签(javascript,ruby)
    • +1 在 JavaScript 中运行良好,很高兴了解 DEMO 链接 :)
    【解决方案3】:

    正如 scibuff 所建议的,在 Ruby 中,最好不要使用正则表达式。

    require 'date'
    date = DateTime.parse("2005:10:29 12:23:53", "%Y:%m:%d %H:%M:%S")
    date.strftime("%Y-%m-%d %H:%M:%S")
    

    【讨论】:

    • 对不起,我删除了混淆标签(javascript,ruby)+1 for ruby​​ 解决方案。
    【解决方案4】:

    再次使用正则表达式来实现更简单、更优雅、更有效的方式

    var date = new Date('2005:10:29 12:23:53');
    

    然后相应地格式化date,例如

    function formatDate( date ){
    
        return date.getFullYear() + '-' + ( get.getMonth() + 1 ) + '-' + ... ;
    
    }
    

    【讨论】:

    • 如果 Date 函数允许 yyyy:mm:dd hh:mm:ss 那就太好了 - 但它不允许。因此,您需要首先将第一组 : 更改为 - 这是 OP 想知道的操作
    • 对不起,我删除了混淆标签(javascript,ruby)
    猜你喜欢
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多