-2

Hi how can i return Grapes from the string below, i want to search through a string and return a text in the middle of the string after four character and discard the rest of the text.

String grapes = "2 x Grapes @Walmart";
TenTen Peter
  • 861
  • 1
  • 15
  • 34

3 Answers3

1

Thanks for helping me guys the code below worked

String grapes = "2 x Grapes @Walmart";
String[] split = grapes.split("\\s+");
String fsplit = split[2];
TenTen Peter
  • 861
  • 1
  • 15
  • 34
0

my suggestion will be not to use a regex for this . But just in case you find no other way round, use this :

(\w+\s){3}

you will get the third word in the first backreference. \1 or $1 whichever supports your compiler

demo here : http://regex101.com/r/jB5nN0

aelor
  • 10,430
  • 3
  • 30
  • 46
-1

This may help you:

^[\\d]+\\sx\\s(.*?)\\s+.*?$

Explanation:

Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
Match a single digit 0..9 «[\d]+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s»
Match the character “x” literally «x»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s»
Match the regular expression below and capture its match into backreference number 1 «(.*?)»
   Match any single character that is not a line break character «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match a single character that is a “whitespace character” (spaces, tabs, and line breaks) «\s+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match any single character that is not a line break character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) «$»
Pedro Lobito
  • 85,689
  • 29
  • 230
  • 253