【发布时间】:2015-05-08 07:27:45
【问题描述】:
所以我正在做一些 cw,我想在一个字符串中搜索主题标签“#”之后的单词。
我该怎么做呢? 例如,字符串是“Hello World #me”?我将如何返回“我”这个词?
亲切的问候
【问题讨论】:
-
我建议使用正则表达式。
-
请发布您现有的代码,您尝试了什么?
标签: java string search substring
所以我正在做一些 cw,我想在一个字符串中搜索主题标签“#”之后的单词。
我该怎么做呢? 例如,字符串是“Hello World #me”?我将如何返回“我”这个词?
亲切的问候
【问题讨论】:
标签: java string search substring
使用 regex 并准备 Matcher 以迭代方式查找主题标签
String input = "Hello #World! #Me";
Pattern pattern = Pattern.compile("#(\\S+)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
输出:
World!
Me
【讨论】:
根据该字符拆分字符串
String []splittedString=inputString.split("#");
System.out.println(splittedString[1]);
所以对于输入字符串
Hello World #me'
输出
me
【讨论】:
ArrayIndexOutOfBoundException 如果输入没有任何#hashtags。
使用这个
example.substring(example.indexOf("#") + 1);
【讨论】:
使用正则表达式:
// Matches a string of word characters preceded by a '#'
Pattern p = Pattern.compile("(?<=#)\\w*");
Matcher m = p.matcher("Hello World #me");
String hashtag = "";
if(m.find())
{
hashtag = m.group(); //me
}
【讨论】:
while 收集所有主题标签。此外,使用\w+ 将仅排除#。
那么约翰,让我猜猜。你是华威大学计算机科学专业的学生。给你,
String s = "hello #yolo blaaa";
if(s.contains("#")){
int hash = s.indexOf("#") - 1;
s = s.substring(hash);
int space = s.indexOf(' ');
s = s.substring(space);
}
如果您不想包含 #,请删除 -1
【讨论】:
#hashtags。
s.substring(space) 会返回什么?