How to change this code with regex

Abad Ashraf

Greenhorn

Posts: 27

posted 1 month ago

This is a homework assignment. I am trying to find a way to convert this code to do the same thing with regex. I can only use the split, matches, and replaceAll regex methods along with length(), indexOf, charAt. contains, substring, replace and equals. What I want is basically if there is a string "cccaaaadddc" the result to get would be c3a4d3c1. The code below does it, but I need to find a way to add regex into it to do the same function. I can only use a single loop, nested is fine. I can only use these regex symbols:

Without groups I don't see where using regular expressions buys you anything over the code you already have. Is using regular expressions a requirement?

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

Abad Ashraf

Greenhorn

Posts: 27

posted 1 month ago

Yeah regex is a requirement, also I cannot use matcher or pattern. I tried to code it somewhat and got a Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 4
[a-z]{jj} error. Just trying with nested loops to see what happens before going single.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

Abad Ashraf

Greenhorn

Posts: 27

posted 1 month ago

I was debugging the code right now and the problem is that it never goes in the if statement, it always goes in the else statement. I believe I also hit an infinite loop since the program never seems to end.

I consider myself pretty good when it comes to regular expressions and I just don't see where regex's help simplify the code you have. Just to meet the letter of the requirements you could use
and the process the array with a loop similar to your original code.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

c is the first character of input
split on everything that's not c
that gives you a string consisting of adjacent c characters
prune off those characters from the beginning of the input string
repeat until input is empty

edit: This is better and shorter.

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.