正则表达式在数字之间有空格时加入数字 [英] Regex to join numbers when they have spaces between them
本文介绍了正则表达式在数字之间有空格时加入数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个正则表达式,当它们之间有空格时,将数字连接到字符串中,例如:
I'm trying to build a regex that joins numbers in a string when they have spaces between them, ex:
$string = "I want to go home 8890 7463 and then go to 58639 6312 the cinema"
正则表达式应该输出:
"I want to go home 88907463 and then go to 586396312 the cinema"
正则表达式可以是python或php语言.
The regex can be either in python or php language.
谢谢!
推荐答案
使用先行查看下一个块是否是一组数字并删除尾随空格.这样,它适用于任意数量的集合(我怀疑你可能想要):
Use a look-ahead to see if the next block is a set of numbers and remove the trailing space. That way, it works for any number of sets (which I suspected you might want):
$string = "I want to go home 8890 7463 41234 and then go to 58639 6312 the cinema";
$newstring = preg_replace("/\b(\d+)\s+(?=\d+\b)/", "$1", $string);
// Note: Remove the \b on both sides if you want any words with a number combined.
// The \b tokens ensure that only blocks with only numbers are merged.
echo $newstring;
// I want to go home 8890746341234 and then go to 586396312 the cinema
这篇关于正则表达式在数字之间有空格时加入数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文