2

I have some symbols in the form of alpha-numeric chars, followed by a single digit. The digit is a year and I need to expand to a two digit year, with 9 becoming 09 and any other year becoming prefixed with 1.

For example:

GCZ0 -> GCZ10
GCZ1 -> GCZ11
...
GCZ8 -> GCZ18
GCZ9 -> GCZ09

I am playing with ([A-Z]+)([9+])([0-9]+) but I'm not sure how to get the replacement to conditionally include the right 0 or 1 prefix.

Could a regex master point me in the right direction please? For unfortunate reasons, I need to do this in a single Java regex match/replace.

Thanks, Jon

3
  • 1
    Please show us the Java code so we can understand the "single Java regex match/replace" restriction. Commented Dec 13, 2010 at 14:39
  • Totally agree with Andrew, we need to know more. Commented Dec 13, 2010 at 14:45
  • Sadly it's part of a vendor product. It's a data import and it allows minimal 'customisation' by letting you apply a single regex transform. Commented Dec 13, 2010 at 14:47

3 Answers 3

7

For unfortunate reasons, I need to do this in a single Java regex match/replace.

Seems doubtful that such a solution exists... the conventional way would be to use Matcher.appendReplacement and Matcher.appendTail to iterate through the source string, find pattern matches, perform arbitrary logic on them, and replace appropriate substitutions.

In Javascript you could use a function with String.replace() as a "smart replacement" rather than a fixed string.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I added a comment above - it's part of a vendor product, the only API hook being a single regex transform on the field. So it looks like I might have to pre-process all the files instead.
0

Edit : Oups, didn't read the single Regex Replace condition ...

Well, never mind about what I suggested ...

Here is the Regex that matches exactly you need :

^[A-Z]{3}9$

Anyway, with a single Replace, I don't see how you could do it ...

I hope someone will be of better help than me.

End Edit

Using StringBuffer, you can insert a char :

StringBuffer sb = new StringBuffer();
sb.append("GCZ0");
if(sb.charAt(3) == '9') sb.insert(2, "0");
else sb.insert(2, "1");

String result = sb.toString();

In result, you have the right String you needed.

1 Comment

@khachik : I don't know if Jon is working with Java 5 or more, nor even if he's in a multi threaded environment or not, so I always go for StringBuffer in this sort of case :)
0

After further investigation, and no other answers here, I've concluded that this isn't possible in a single Java regexp.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.