如果前四个字符是数字,则在字符串中插入字符

我有一个字符串,其中每次有数字时都没有空格。我想创建它并添加一个逗号。

例如,以下内容:

2013 Presidential2008 Presidential2016 Parliamentary - Majoritarian Runoff2016 Parliamentary - Majoritarian Rerun

将转换为:

2013 Presidential,2008 Presidential,2016 Parliamentary - Majoritarian Runoff2016 Parliamentary - Majoritarian Rerun

直到现在我有了:

for char in s:
...     if char.isalpha():
            ???

我也尝试过使用Javascript:

function isnumber(c) {
    return (i >= '0' && i <= '9');
}
for (var x = 0; x < text.length; x++)
{
    var c = text.charAt(x);
    if isnumber(i){
        // add a "," before and move to the next char which is a letter
        text[:x] + ',' + text[x:]
    }   
}

但是它返回:Uncaught SyntaxError: Unexpected identifier

yyl000831 回答:如果前四个字符是数字,则在字符串中插入字符

查看replaceAllmdn)。

String

如果您输入的数字后面已经有一个空格,那么可以通过稍微修改正则表达式来确保不添加逗号:

string.prototype.replace

,

在Python上使用正则表达式:

import re

text = '2013 Presidential2008 Presidential2016 Parliamentary - Majoritarian Runoff2016 Parliamentary - Majoritarian Rerun'

pat = re.compile(r'([^\d\s])(\d+)')
pat.sub(r'\1,\2',text)

输出:

'2013 Presidential,2008 Presidential,2016 Parliamentary - Majoritarian Runoff,2016 Parliamentary - Majoritarian Rerun'

示例:https://regex101.com/r/tDdfsc/1

本文链接:https://www.f2er.com/3150819.html

大家都在问