Link to home
Start Free TrialLog in
Avatar of chenwei
chenwei

asked on

How to abstract a sub-string fro ma string by using Regular Expression?

Assumed I have a string as follow:

"ÖÄÖÜ Stand:¶R **üü 12.02.2009ÿÂ"

What I want is, I want to abstract the date "12.02.2009" from this string. I guess one can do this in a simple way by using Regular-Expression.

Has someone idea?
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Try the following:
s = s.replaceAll(".*\\d{2]\\.\\d{2}\\.\\d{4}.*", "$1");

Open in new window

Oops sorry
  	
 
s = s.replaceAll(".*(\\d{2]\\.\\d{2}\\.\\d{4}).*", "$1");

Open in new window

Yes regex is what you need

String input = "ÖÄÖÜ Stand:¶R **üü 12.02.2009ÿÂ";
Pattern pattern = Pattern.compile(".*([0-9]{2}\\.[0-9]{2}\\.[0-9]{4}).*");
Matcher matcher = pattern.matcher(input);
matcher.find();
System.out.println(matcher.group(1));

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of chenwei
chenwei

ASKER

I do as follow:

      private static final String STAND = "ÖÄÖÜ   Stand:¶R **üü 12.02.2009ÿÂ";
      /**
       * @param args
       */
      public static void main(String[] args) {

            String subStr = STAND.replaceAll(".*\\d{2]\\.\\d{2}\\.\\d{4}.*", "$1");
            System.out.println(subStr);
      }


But I get exception as follow:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed counted closure near index 6
.*\d{2]\.\d{2}\.\d{4}.*
      ^

So I correct your regular-expression as follow:
".*\\d{2}\\.\\d{2}\\.\\d{4}.*", "$1"

But I get exception as follow:

Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 1
      at java.util.regex.Matcher.group(Matcher.java:463)
      at java.util.regex.Matcher.appendReplacement(Matcher.java:730)
      at java.util.regex.Matcher.replaceAll(Matcher.java:806)
      at java.lang.String.replaceAll(String.java:2000)
      at com.weichen.app.alltest.FilterSubString.main(FilterSubString.java:11)
See my correction
Avatar of chenwei

ASKER

I think the correct expression should be:
replaceAll(".*(\\d{2}\\.\\d{2}\\.\\d{4}).*", "$1");

The first ']' should be '}'. :-)

Many thanks!
So sorry chenwei - there was still a typo in there, so
  	
 
String date = s.replaceAll(".*(\\d{2}\\.\\d{2}\\.\\d{4}).*", "$1");

Open in new window

Avatar of chenwei

ASKER

Simply wonderful.
:-)