1

I am dealing with a String,

30-Nov-2012 30-Nov-2012 United Kingdom, 31-Oct-2012 31-Oct-2012 United Arab Emirates, 29-Oct-2012 31-Oct-2012 India 

I need to add spaces every time a space appears after a four digit numbers, i.e.:

30-Nov-2012@30-Nov-2012@United Kingdom, 31-Oct-2012@31-Oct-2012@United Arab Emirates, 29-Oct-2012@31-Oct-2012@India 

I don't know how to write Regular Expressions, any help please?

3
  • 1
    Well, have you tried to learn how to write regular expressions? Have you read the documentation for java.util.regex.Pattern?
    – Jon Skeet
    Oct 31, 2012 at 7:07
  • You want to add '@' every time a space appears after a four digit numbers as seen in your example Oct 31, 2012 at 7:08
  • KishorSharma yes, you are correct. JonSkeet please can you share appropriate resources ?
    – onkar
    Oct 31, 2012 at 7:10

2 Answers 2

1

Since you don't know how to write Regular Expressions, your best bet is learning how to use Regular Expressions.

Here's a pretty good tutorial.

http://www.vogella.com/articles/JavaRegularExpressions/article.html

The expression you want to write doesn't seem very complicated. You should be able to do it after going through this tutorial.

Edit: Here's another hint. Take a look at replaceAll

and also take a look at positive lookbehinds

Edit2: I'm bored, so here's the answer.

string.replaceAll("(?<=\\d{4})\\s", "@");
3
  • Give it a try and see if it works. There are a bunch of sites online that let you test regular expressions. Here's one: regexplanet.com/advanced/java/index.html
    – Michael
    Oct 31, 2012 at 7:18
  • @onkar I updated my answer with a possible solution. Let me know if it doesn't work (it should).
    – Michael
    Oct 31, 2012 at 7:25
  • Try again, I forgot to paste it as code so it lost some '\'s.
    – Michael
    Oct 31, 2012 at 7:28
1

Try this regex:

(\d{4})\s+

replace with

$1@

and a sample code:

String result = inputString.replaceAll("(\\d{4})\\s+", "$1@");

explain:

\d Matches any decimal digit.

{n} Matches the previous element exactly n times.

\s Matches any white-space character.

+ Matches the previous element one or more times.

(subexpression) Captures the matched subexpression and assigns it a zero-based ordinal number.

$ number Substitutes the substring matched by group number.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.