1

I'm struggling to get a regex expression to work.

I need to allow the following transforms based on the existence of leading zeros...

  1. 001234 -> 1234
  2. 1234 -> 1234
  3. 00AbcD -> AbcD
  4. 001234.1234 -> 1234.1234
  5. 001234.000002 -> 1234.2
  6. 001234/000002 -> 1234.2

I've found the expression matches works well for transforms 1, 2 & 3 but I'm not sure how to match the (optional) second section demonstrated in 4, 5 & 6.

^0*([0-9A-Za-z]*$)
4

2 回答 2

2

您可以使用以下正则表达式获得零:

/(?:^|[./])0+/g

演示

并将第二组替换为第一组 ( \1)。

例如在 python 中,我可以执行以下操作:

>>> s="""001234
... 1234
... 00AbcD
... 001234.1234
... 001234.000002
... 001234/000002"""

>>> [re.sub(r'(:?^|[./])0+',r'\1',i) for i in s.split()]
['1234', '1234', 'AbcD', '1234.1234', '1234.2', '1234/2']
于 2015-06-12T11:00:46.940 回答
0
^(0+)(.+)

第 2 组应该是结果。

于 2015-06-12T11:03:20.723 回答