我有一个很长的字符串模式匹配的字符串数组让我们说获取从字符串
我知道正则表达式模式是
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
现在,我想所有的主题标签在一个数组中。我如何使用这个表达式来获取字符串中所有散列标签的数组,如
ArrayList hashtags = getArray(pattern, str)
我有一个很长的字符串模式匹配的字符串数组让我们说获取从字符串
我知道正则表达式模式是
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
现在,我想所有的主题标签在一个数组中。我如何使用这个表达式来获取字符串中所有散列标签的数组,如
ArrayList hashtags = getArray(pattern, str)
你可以这样写吗?你
private static List<String> getArray(Pattern tagMatcher, String str) {
Matcher m = tagMatcher.matcher(str);
List<String> l = new ArrayList<String>();
while(m.find()) {
String s = m.group(); //will give you "#computer"
s = s.substring(1); // will give you just "computer"
l.add(s);
}
return l;
}
也可以用\\w-
代替A-Za-z0-9-_
使得正则表达式[#]+[\\w]+\\b
好的答案,你能告诉我正则表达式中的'\\ b'是什么? – Keerthivasan
@Octopus专门[边界匹配器](http://docs.oracle.com/)经过[Lesson:Regular Expressions](http://docs.oracle.com/javase/tutorial/essential/regex/index.html) javase/tutorial/essential/regex/bounds.html) – Justin
@Octopus他为你做了什么感谢(除了一个很好的答案)? – Justin
This link肯定会实现你想要的帮助。
它说:
的find()方法中传递给Pattern.matcher(文本)方法,当 匹配器创建的文本正则表达式 的出现方法搜索。如果可以在文本中找到多个匹配项,则find()方法将找到第一个匹配项,然后对于每个后续调用 find()它将移动到下一个匹配项。
方法start()和end()会将索引赋予文本 ,其中找到的匹配开始和结束。
例子:
String text =
"This is the text which is to be searched " +
"for occurrences of the word 'is'.";
String patternString = "is";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
int count = 0;
while(matcher.find()) {
count++;
System.out.println("found: " + count + " : "
+ matcher.start() + " - " + matcher.end());
}
你现在得到的提示。
这里有一种方法,使用Matcher
Pattern tagMatcher = Pattern.compile("#+[-\\w]+\\b");
Matcher m = tagMatcher.matcher(stringToMatch);
ArrayList<String> hashtags = new ArrayList<>();
while (m.find()) {
hashtags.add(m.group());
}
我把简化你的正则表达式的自由。 #
不需要在角色类中。 [A-Za-z0-9_]
相同\w
,所以[A-Za-z0-9-_]
相同[-\w]
您可以使用:
String val="I like this #computer and I want to buy it from #XXXMall.";
String REGEX = "(?<=#)[A-Za-z0-9-_]+";
List<String> list = new ArrayList<String>();
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(val);
while(matcher.find()){
list.add(matcher.group());
}
(?<=#)
正回顾后 - 断言字符#
字面匹配。
您可以使用下面的代码获取名称
String saa = "#{akka}nikhil#{kumar}aaaaa";
Pattern regex = Pattern.compile("#\\{(.*?)\\}");
Matcher m = regex.matcher(saa);
while(m.find()) {
String s = m.group(1);
System.out.println(s);
}
它将打印
akka
kumar
分割字符串与空间 - >转换成列表 - >在列表循环运行,并获取匹配的值 –
可能的重复[如何使用Java Regex查找字符串中的所有重复字符序列?](http://stackoverflow.com/questions/10287685/how-do-i-use-java-regex-to-find-all-repeating-character-sequences-in-a-string) – FWeigl