+ 2
Java problem regex
Hello everyone, Iām new to java and need help. I need to capitalize the pronoun I in an input string and I was told a regex would help but I donāt know where to start. I already managed to do it using a replaceAll. However this doesnāt involve cases like Ā«neither do I.Ā» - input : i donāt know what iām writing. Neither do i. Maria, iāll let you know when i can. -output : I donāt know what Iām writing. Neither do I. Maria, Iāll let you know when I can.
9 Answers
+ 4
Hello.
You asked for a solution with regular expressions.
Here is how you can do it with Java.
Pattern.compile("\\bi\\b");
To explain, you want to capture the character lowercase i when it is a single word. The \b control character means a word boundary, this includes whitespace and punctuation such as apostrophe and dot also.
In Java, you need to double-escape the backslashes in the regexp control codes, so it looks a bit weird compared to other languages.
The Pattern object represents a regular expression, the Matcher object applies this to a specific string (text).
Then Matcher has the replaceAll method which does just what you want.
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html
https://code.sololearn.com/ctRRbsTKRgHq/?ref=app
+ 1
Do you have the code to share?
In your above text, it looks like you have a space between either your inverted commas ' or backticks ` and your letters.
+ 1
You could do some if/else if checks to cover all bases and only capitalise the pronouns that way.
+ 1
1.U can do a loop that will start with the idx=0 to idx=last-2of the string.
2.State a condition that if charAt(idx) =='i' and Character.isLetter(charAt(idx+1) ) == false.
3.one more condition if (chaAt(idx-1) == 'i' and charAt(idx-2) ==' ').
4 . Statement within the condition will be.
A empty string declared out side the loop. Say string x="";
X+=Chracter.toUpperCase(charAt(idx) ) ;
5.else part
X+= charAt(idx) ;
Hope so it helpsm
+ 1
Tibor Santa you are my savior!!! Thank you so so much!!!
0
Thatās not really the problem, that was just an example. I have a space before and after the letter i on purpose because I need the pronoun i to be capitalized in the sentence but I donāt want to keep using replaceAll for each case.
- input : i donāt know what iām writing. Neither do i. Maria, iāll let you know when i can.
-output : I donāt know what Iām writing. Neither do I. Maria, Iāll let you know when I can.
0
I thought of that but I wanted a method with regex to shorten the code, thanks though!
0
Include in the question description a link to your code in Code Playground, and we will help find the problem and the solution.
That said, you probably have a problem detecting words. Let's see what the code shows us.
0
Thank you suvam ghosh, Iāll try that out!