-1

I never was good enough with regex, and I assume this is the job for it.

I have a link like 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.

What I need is to find an occurence of string contains of 'sz' + number and replace it with 'sz=100'.

Sure, I can do that 'manually" in some for loop, but that wouldn't be nor smar nor efiicient.

Cœur
  • 32,421
  • 21
  • 173
  • 232
Jacek Kwiecień
  • 11,495
  • 19
  • 75
  • 148
  • Just some dumb for loop, since I really suck in regex :/ Wouldnt mention it – Jacek Kwiecień Apr 11 '14 at 18:35
  • 2
    Have you tried a regex tutorial? Are you willing to learn or just looking for a solution to be handed to you? If you're willing to learn, start here: http://docs.oracle.com/javase/tutorial/essential/regex/ If not, just wait and somebody will spoon-feed you a solution. – Mike B Apr 11 '14 at 18:36
  • Spoon-feeding was just something I needed right now. I believe somebody will also make use of it – Jacek Kwiecień Apr 11 '14 at 18:42
  • Please consider bookmarking the [Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/2736496) for future reference. One answer that may interest is [validating urls](http://stackoverflow.com/a/190405/2736496), which is listed under "Common Validation Tasks". There's also a section of online testers at the bottom. – aliteralmind Apr 13 '14 at 19:01

3 Answers3

3
str = "www.somelink/phoyto.jpg/?sz=50";
str.replaceall("sz=\\d+", "sz=100");

\d is the java pattern for digit. + stands for one or more digits. replaceall replaces all occurrences of sz=<number>.

Here is a handy online regex tester for java: http://www.regexplanet.com/advanced/java/index.html

Sudeep Juvekar
  • 4,308
  • 2
  • 28
  • 35
  • 1
    Good explanation, however, the criticism I have about this answer is that the replacement is incorrect according to the question. The replacement is supposed to be `sz100` looking at what was posted; here it's `sz=100` — so which is it? I might suggest stackoverflow.com needs an `incorrect correct answer` button for these scenarios. :D – l'L'l Apr 11 '14 at 19:13
  • The correct answer of SO is from the OP's perspective – spiderman Apr 11 '14 at 19:34
  • Answer is fully correct, questions has a typo, which I corrected – Jacek Kwiecień Apr 13 '14 at 18:55
2

This should work:

String link = "www.somelink/phoyto.jpg/?sz=50";
link = link.replaceFirst("sz=\\d+", "sz=100");
System.out.println(link);
DanW
  • 237
  • 1
  • 8
1

It's pretty simple, and this pattern should work:

(sz=\d+)

Code:

String result = searchText.replaceAll("(sz=\\d+)", "sz100");

Example:

http://regex101.com/r/mB3xT9

l'L'l
  • 40,316
  • 6
  • 77
  • 124