【发布时间】:2016-04-10 10:41:49
【问题描述】:
有谁知道如何替换此类字符串中的数字并删除第二部分(如果存在)?
我知道这听起来很奇怪,让我解释一下。
每次处理的字符串都不一样:
数字(我需要替换的)可以从1 数字到10 数字,从:0 到:9999999999(也可以是零0000000000)。
数字前总是有一个字符(可以是任何字符,任何大小写),例如:X0000、a00、h000000、G000。
有时后面可能会有其他部分(以连字符开头,如果存在,我需要删除这部分),例如:X000-X00000、X0000-X00、X00-X0。
有时可能会有另一个额外的字符(可以是任何字符,任何情况下,以连字符开头,如果存在,我需要保留这部分),例如:X00000-X、X0000-X000-X、a000-h、@ 987654338@.
我不知道如何替换第一部分(如果存在),删除第二部分(如果存在)并保留最后一部分(如果存在),这是我需要的示例:
X0000 > X1234
a00 > a12
h000000 > h123456
G000 > G123
X000-X000000 > X123 - replace the first and delete the last
X0000-X000 > X1234 - replace the first and delete the last
X00-X00 > X12 - replace the first and delete the last
X00000-X > X12345-X - replace only the first and keep the last
a000-h > a123-h - replace it and keep the last
X0000-X000-X > X1234-X - replace the first, delete the second and keep the last
g00000-j00-Y > g12345-Y - replace the first, delete the second and keep the last
在这个例子中,我主要使用 0 和 X,但就像解释的那样,可以是 0 或任何数字,也可以是 X 或任何字符(大写或小写)。
编辑:忘了提,我需要得到那个数字,用它做数学运算然后替换它,不仅仅是替换。
有人知道怎么做吗?非常感谢。
【问题讨论】:
-
你需要开始使用正则表达式
-
我编辑了我的问题,我忘了提到最后一部分,关于如何使用正则表达式的任何想法?谢谢。
标签: java android string android-studio str-replace