0

I have a string like this :

"value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>"

I want to extract the string value of <abc/def> does not end with <abc>.
I used following pattern

String text = "value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>";
String patternString1 = "(value\\s+of\\s+(<.*>)\\s+ends\\s+with\\s+(<.*>))";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
    System.out.println("found: " + matcher.group(1));
}

Results :-

found: value of <abc/def> ends with <def> and value of <abc/def> does not end with <abc> and value of <abc> is <abc>
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 1
    `.*` is [greedy](http://stackoverflow.com/q/2301285/2071828) by default. You would need to make it lazy by adding a `?`. At least I think that is the issue - I don't really understand the question. – Boris the Spider Mar 31 '14 at 11:13
  • I don't really know what you really mean but maybe modifying the greed of the `*` will do the trick, to `*?`. This will grab the least characters possible. – Javier Diaz Mar 31 '14 at 11:15
  • Why is your regex trying to match the `ends with`-part whereas you say, you want to match the `does not end with`-part? It's somehow confusing. – Jonny 5 Mar 31 '14 at 11:30

3 Answers3

2

As you mean to get value of <abc/def> does not end with <abc> the pattern after the correction:

String patternString1 = "(value\\s+of\\s+(<[^>]*>)\\s+does\\s+not\\s+end\\s+with\\s+(<[^>]*>))";
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
0

Try using below code for this.

String text = "value of ends with and value of does not end with and value of is ";
String arr[] = text.split(" and ");
System.out.println(arr[1]);

This splits string into three parts.This would help you.

Cast_A_Way
  • 472
  • 5
  • 19
  • Thanks...But the problem is all the characters between <> are variables. any string can come. like or or . So we cam't use static string to split. – user3480752 Mar 31 '14 at 11:27
0

Use .endsWith()

if (!<abc/def>.endsWith(<abc>) {
   // do stuff ...
}

I put the ! so it only happens when it doesn't end with

Stephan
  • 41,764
  • 65
  • 238
  • 329
Joe's Morgue
  • 173
  • 2
  • 8