Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Regex question

Status
Not open for further replies.

LuckyKoen

Programmer
Feb 14, 2005
57
BE
I am trying to replace one string with another one. The string that needs to be replaced can't end on a letter or number. I have the following regex at the moment :

myString.replaceAll("cloud[^a-z0-9A-Z]", "sun");

As expected, this regex will skip the word "clouds" but will replace the word "cloud#". In the 2nd case, both "cloud" and "#" will be replaced with "sun". How do I keep this # character so that the result of the regexp is sun# and not sun ?
 
works for me...
Code:
String myString = "The clouds are cloudy.  Cloud#, cloud#, cloud$, cloud! and clouded.";
myString = myString.replaceAll("cloud[^a-z0-9A-Z]", "sun");
System.out.println("myString: " + myString);
results in:
myString: The clouds are cloudy. Cloud#, sun, sun, sun and clouded.

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
Jemm, the result I would like to get when using your String is:
myString: The clouds are cloudy. Cloud#, sun#, sun$, sun! and clouded.

Instead of :
myString: The clouds are cloudy. Cloud#, sun, sun, sun and clouded.
 
You catch the concrete character(s), matching your expression, with, with '()'.
To distinguish the braces from braces, meant as token, you have to mask them with backslashes: '\(, \)'.
A backslash is used for masking special characters in java-source, so you have to mask the backslash with a backslash, if you mean a backslash as such: "\\(expression\\)".
If you would read the expression from a file, you would use single backslashes.

To reference the content of the expression, you use '$N', with N being the sequence-number of the captured expression (you may use multiple capturings, and counting is done by opening braces).

Code:
String myString = "The clouds are cloudy.  Cloud#, cloud#, cloud$, cloud! and clouded.";
myString = myString.replaceAll("cloud\\([^a-z0-9A-Z]\\)", "sun$1");
System.out.println("myString: " + myString);

seeking a job as java-programmer in Berlin:
 
ok - misunderstood the question. stefan's example looks right

-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
i like your sleeves...they're real big
 
Thanks for the help Stefan.

The double backslashes weren't necessary. The following line worked nicely :

myString = myString.replaceAll("cloud([^a-z0-9A-Z])", "sun$1");


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top