开发者

Using regex to reformat text

Is there a way to use regex to reformat a string?

I've a string like this AEY4293 and I want to add a dash between letters and numbers, like this AEY-4293.

I was trying to find something like s/pattern/replacement/, but I couldn't find it.

I can select t开发者_开发技巧he blocks using /(\w+)(\d+)/ so if I could give to a pattern to reformat the text like \1-\2 it would be great.

Thanks!


irb(main):001:0> "AEY4293".sub(/(\D+)(\d+)/, '\1-\2')
=> "AEY-4293"


'AEY4293'.sub(/(?<=\w)(?=\d)/, '-')

You can also do

'AEY4293'.sub(/(?=\d)/, '-')

which comes close to mu is too short's answer.


Regex would be:

/([A-Z]+)(\d+)/

Replacement pattern would be:

\1-\2

There is a problem with expression /(\w+)(\d+)/, because \w matches both alpha and numbers. So, with input AEY4293, \w+ will match AEY429 and \d+ will match trailing 3.


If the non-numeric prefix is always three characters then you can do it without a regular expression:

s = 'AEY4293'
s[3,0] = '-'
# s is now 'AEY-4293'

Or, if you want a little more flexibility on the prefix size, you can use index combined with the above:

s[s.index(/\d/), 0] = '-'

I like the bracket-assignment notation for this as it matches up nicely with your intent.


There is a str.sub(pattern, replacement) method for that. Replacement is a sting with \1 and so on references.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜