[英]Eliminating spaces and words starting with particular chars from JAVA string
[英]Extract words starting with a particular character from a string
我得到以下字符串:
String line = "#food was testy. #drink lots of. #night was fab. #three #four";
我想利用#food
#drink
#night
#three
和#four
从它。
我试过这段代码:
String[] words = line.split("#");
for (String word: words) {
System.out.println(word);
}
但是它让food was testy
, drink lots of
, nigth was fab
, three
和four
。
split
只会在发现#的位置切断整个字符串。 这解释了你目前的结果。
您可能想要提取每个字符串的第一个单词,但执行任务的好工具是RegEx
在这里你如何实现它:
String line = "#food was testy. #drink lots of. #night was fab. #three #four";
Pattern pattern = Pattern.compile("#\\w+");
Matcher matcher = pattern.matcher(line);
while (matcher.find())
{
System.out.println(matcher.group());
}
输出是:
#food
#drink
#night
#three
#four
魔术发生在“#\\ w +”中。
#
模式以#开头 \\w
匹配任何字母(az,AZ),数字(0-9)或下划线 。 +
匹配一个或多个连续的\\w
字符。 因此,我们搜索以#
开头,后跟一个或多个字母,数字或下划线的内容。
由于Escape Sequences,我们使用'\\\\'作为'\\'。
你可以在这里玩。
find
和group
在这里解释:
find
方法扫描输入序列,寻找与模式匹配的下一个子序列。 group()
返回上一个匹配项匹配的输入子序列。 [编辑]
如果您需要检测重音字符或非拉丁字符,则使用\\w
可能是一个问题。
例如:
“Bonjour mon#bébé#chat。”
比赛将是:
这取决于你将接受什么样的hashTag 。 但这是另一个问题, 关于它 存在 多种 讨论 。
例如,如果您想要任何语言的任何字符, #\\p{L}+
看起来不错,但下划线不在其中......
请按照以下步骤进行操作==>
String candidate = "#food was testy. #drink lots of. #night was fab. #three #four";
String regex = "#\\w+";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(candidate);
String val = null;
System.out.println("INPUT: " + candidate);
System.out.println("REGEX: " + regex + "\r\n");
while (m.find()) {
val = m.group();
System.out.println("MATCH: " + val);
}
if (val == null) {
System.out.println("NO MATCHES: ");
}
这将给出如下输出,因为我解决了我的netbeans IDE的问题,并测试了该程序
INPUT: #food was testy. #drink lots of. #night was fab. #three #four
REGEX: #\w+
MATCH: #food
MATCH: #drink
MATCH: #night
MATCH: #three
MATCH: #four
您将需要以下导入
import java.util.regex.Matcher;
import java.util.regex.Pattern;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.