• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

More Regex Help

 
Joel Christophel
Ranch Hand
Posts: 250
1
Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want the following code to replace any apostrophes that come after a letter that is not s with an exclamation point. The program isn't even reaching the body of the if statement. What am I doing wrong?

 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
contains, lastIndexOf and replace do not work with regular expressions. There are only two methods of String that do - replaceAll and matches. I think you'll want to use an explicit Pattern / Matcher pair here. Or, if you use a negative lookbehind, you can use replaceAll:
This negative lookbehind, (?<![sS]), will cause only apostrophes that are not preceded by an s or S to be replaced.
 
Darryl Burke
Bartender
Posts: 5126
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:contains, lastIndexOf and replace do not work with regular expressions. There are only two methods of String that do - replaceAll and matches.

<nitpick>
Four. replaceFirst(...) and (two overloads of) split(...).
</nitpick>
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never used replaceFirst so that explains why I missed that, but missing split? Jeeez....
 
Winston Gutkowski
Bartender
Pie
Posts: 10417
63
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joel Christophel wrote:I want the following code to replace any apostrophes that come after a letter that is not s with an exclamation point. The program isn't even reaching the body of the if statement.

Between this and your previous thread, I suspect you're tackling this problem existentially, which is not usually a good way to go.

My advice:
1. Forget about regexes.
2. Turn OFF your computer.
3. Sit down and write out in English what it is you want to do.
4. When you've done that, think about scenarios that might cause problems. Again, write out solutions for them in English.

5. (Only when you're sure you've done a good job of 3 and 4) Turn your computer back on and try and code your results in Java. You may even find that regexes are NOT what you want for everything.

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic