Java 格式化字符串以查找和替换段
我有以下Java字符串Java 格式化字符串以查找和替换段,java,string,Java,String,我有以下Java字符串 String abc="My name 233:23 is Shefali MNT+2:199999' MNT+12:40 xyzpqrst"; 我希望前面的数字后面跟着MNT+2,然后冒号(:)即199999应替换为1,字符串的其余部分应保持不变 i、 e。 O/p应该是“我的名字233:23是Shefali MNT+2:1'MNT+12:40 xyzpqrst” 第二例>> 如果输入字符串是“ABC:MNT+232421:9'MNT+39191:hks” O/p应为
String abc="My name 233:23 is Shefali MNT+2:199999' MNT+12:40 xyzpqrst";
我希望前面的数字后面跟着MNT+2
,然后冒号(:)即199999应替换为1,字符串的其余部分应保持不变
i、 e。
O/p应该是“我的名字233:23是Shefali MNT+2:1'MNT+12:40 xyzpqrst”
第二例>>
如果输入字符串是“ABC:MNT+232421:9'MNT+39191:hks”
O/p应为“ABC:MNT+232421:1'MNT+39191:hks”
我试了很多东西,但都没弄明白
有人能帮忙吗?您可以使用以下正则表达式:
(MNT\+\d+):\d+'
并使用此替换字符串:$1:1'
查看它的实际操作:使用replaceAll()
您可以使用一些分组表达式,例如
String[] arr = { "My name 233:23 is Shefali MNT+2:199999' MNT+12:40 xyzpqrst",
"ABC : MNT+232421:9' MNT+39191: hks" };
String[] out = { "My name 233:23 is Shefali MNT+2:1' MNT+12:40 xyzpqrst",
"ABC : MNT+232421:1' MNT+39191: hks" };
Pattern p = Pattern.compile("(.*):(\\d+)'(.*)");
for (int i = 0; i < arr.length; i++) {
Matcher m = p.matcher(arr[i]);
if (m.matches()) {
String t = m.group(1) + ":1'" + m.group(3);
System.out.printf("%s = %s %s%n", t, out[i], t.equals(out[i]));
}
}
使用正则表达式使用replaceAll()
String abc="My name 233:23 is Shefali MNT+2:199999' MNT+12:40 xyzpqrst";
abc.replaceAll("(MNT\\+\\d+):\\d+'", "$1:1'")
它将取代给定模式的所有发生。
< P>一个正则表达式是比较简单的,但是为了比较,让我们看看另一种方式。String abc="My name 233:23 is Shefali MNT+2:199999' MNT+12:40 xyzpqrst";
//get index of the start of first "MNT"
int mntIndex = abc.indexOf("MNT+2:");
//get index of the second "MNT" location
int mntIndex2 = abc.indexOf("' MNT", mntIndex);
//now set abc equal to a substring up to the end of "MNT+2:"
//adding 6 (the length of "MNT+2:")
//manually adding "1"
//finishing with a substring of abc starting
//from the "' MNT" index up to the end of abc (abc.length())
abc = abc.substring(0, mntIndex) + 1 + abc.substring(mntIndex2,abc.length());
String abc="My name 233:23 is Shefali MNT+2:199999' MNT+12:40 xyzpqrst";
abc.replaceAll("(MNT\\+\\d+):\\d+'", "$1:1'")
String abc="My name 233:23 is Shefali MNT+2:199999' MNT+12:40 xyzpqrst";
//get index of the start of first "MNT"
int mntIndex = abc.indexOf("MNT+2:");
//get index of the second "MNT" location
int mntIndex2 = abc.indexOf("' MNT", mntIndex);
//now set abc equal to a substring up to the end of "MNT+2:"
//adding 6 (the length of "MNT+2:")
//manually adding "1"
//finishing with a substring of abc starting
//from the "' MNT" index up to the end of abc (abc.length())
abc = abc.substring(0, mntIndex) + 1 + abc.substring(mntIndex2,abc.length());