We help IT Professionals succeed at work.
Get Started
Troubleshooting Question

How to use alternation when using regular expressions in Java

babyb00mer
babyb00mer asked
on
168 Views
Last Modified: 2020-12-20
So here's my dilemma…

I'm using Java to write a program in which I'd like to use regular expressions to parse a string and insert a character at regular intervals. For those of you familiar with Java, I'm using the string class's replaceAll method to accomplish the task. Specifically, I'd like to insert spaces between groups of digits that represent binary, hexadecimal or octal numbers. For example, between every four digits of a binary number, I want to insert a space. Likewise, the digits representing a hexadecimal number would be grouped by twos, and the digits in a string representing an octal number would be grouped by threes. For example, the binary number "11110110" would be replaced by "1111 0110." Ideally, I'd like to devise a single expression to accomplish the task, regardless of the base (i.e., binary, hexadecimal or octal) of the number that the string contains. In other words, I'd rather not have to code three separate calls to the replaceAll method. I have tried alternation using the "or" (|) operator, but without much success.

The other issue is that the digits in the string must be grouped from right to left, which is contrary to the way in which the parser works. To get around that limitation I've been reversing the order of the characters in the string prior to performing the replacement. Afterwards, I reverse the order again.

Years ago I was pretty good at regular expressions. Even so, this challenge might be beyond any expertise I ever attained. Perhaps it can't be done. Any assistance would be greatly appreciated!

Comment
Watch Question
CERTIFIED EXPERT
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 4 Answers and 34 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE