Conditional replace in a single Java regex expression
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.
Than开发者_开发知识库ks, Jon
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.
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.
After further investigation, and no other answers here, I've concluded that this isn't possible in a single Java regexp.
精彩评论