简体   繁体   中英

java string.getIndex correct index ignoring punctuation

If I had a string like this one that has punctuation like ,, ?, ;, , what if I wanted to use string.indexOf(); to search for a string such as " like ", and get back the index?

If I remove all punctuation I could search it but because of the punctuation earlier it would give me the wrong index in the string. Is there a built-in way in Java to do such a thing? I have a workaround in mind I am going to test but won't bother if there's a proper way.

Yes, there is! It is called regular expressions .

Build a regex matching your punctuation and seeked substring, and search for it.

You might want to also have a look at the Matcher and Pattern classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM