我有一個很長的字符串模式匹配的字符串數組讓我們說獲取從字符串
我知道正則表達式模式是
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