搜索字符串并返回特定文本android

时间:2014-04-22 13:50:13

标签: android regex string

您好我如何从下面的字符串返回Grapes,我想搜索一个字符串并在四个字符后面的字符串中间返回一个文本并丢弃其余文本。

String grapes = "2 x Grapes @Walmart";

3 个答案:

答案 0 :(得分:1)

感谢您帮助我们以下代码

String grapes = "2 x Grapes @Walmart";
String[] split = grapes.split("\\s+");
String fsplit = split[2];

答案 1 :(得分:0)

我的建议是不要使用正则表达式。但是,万一你找不到其他方法,请使用:

(\w+\s){3}

您将在第一个反向引用中获得第三个单词。 \1$1支持您的编译器

演示:http://regex101.com/r/jB5nN0

答案 2 :(得分:-1)

这可能会对您有所帮助:

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

<强>解释

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) «$»
相关问题