I need to count number of times a single quote appears in a string but excluding those cases where single quote is directly followed by a single quote.
Example:
'singlequote','another single quote'
should give count 4 and
'singlequote','2 quote'' inside single quote'
should also give count 4
I did this
char quote= '\'';
int count2 = string.replaceAll("[^"+ quote +"]", "").length();
but this counts all the occurences.
Is there a way to do it in regex or do i need to loop through all the characters. Can someone please help with this
You can use this look-around based regex to match single quotes that are not preceded or followed by any single quote. Note that it will skip all the cases of multiple quotes so double or triple quotes will not be matched.
(?<!')'(?!')
RegEx Breakup:
(?<!')
- Assert if previous character is not a single quote '
- Match a single quote (?!')
- Assert if next character is not a single quote You can replace all ''|[^']
in your string. It will replace all 2 single quotes and everything else but a single quote.
Example:
int count2 = string.replaceAll("''|[^']", "").length();
Which gives output 4
;
See DEMO: https://ideone.com/PqtRu6
Here's another way to do that, replace all 2-consecutive quotes with an empty string and count occurrences:
StringUtils.countOccurrencesOf(yourString.replaceAll("''", ""), "'")
Make sure you import:
import org.springframework.util.StringUtils;
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.