[英]Replacing occurrences of generic string
I never was good enough with regex, and I assume this is the job for it. 我对regex从来都不是很满意,我认为这是它的工作。
I have a link like www.somelink/phoyto.jpg/?sz=50
我有一个类似
www.somelink/phoyto.jpg/?sz=50
I need to replace 50 with my value, let's say 100. Trouble is, that I cannot be sure, that this will be always sz=50
and not sz=150
or sz=10
or any other value. 我需要用我的值(例如100)替换50。麻烦的是,我不确定这将始终是
sz=50
而不是sz=150
或sz=10
或任何其他值。
What I need is to find an occurence of string contains of 'sz' + number
and replace it with 'sz=100'
. 我需要查找包含
'sz' + number
的字符串,并将其替换为'sz=100'
。
Sure, I can do that 'manually" in some for loop, but that wouldn't be nor smar nor efiicient. 当然,我可以在for循环中“手动”执行此操作,但这既不明智,也不有效。
str = "www.somelink/phoyto.jpg/?sz=50";
str.replaceall("sz=\\d+", "sz=100");
\\d
is the java pattern for digit. \\d
是数字的Java模式。 +
stands for one or more digits. +
代表一个或多个数字。 replaceall
replaces all occurrences of sz=<number>
. replaceall
替换所有出现的sz=<number>
。
Here is a handy online regex tester for java: http://www.regexplanet.com/advanced/java/index.html 这是一个方便的Java在线正则表达式测试器: http : //www.regexplanet.com/advanced/java/index.html
This should work: 这应该工作:
String link = "www.somelink/phoyto.jpg/?sz=50";
link = link.replaceFirst("sz=\\d+", "sz=100");
System.out.println(link);
It's pretty simple, and this pattern should work: 这很简单,这种模式应该可以工作:
(sz=\d+)
Code: 码:
String result = searchText.replaceAll("(sz=\\d+)", "sz100");
Example: 例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.