如果我有一個正則表達式,我該如何返回它找到的子字符串? 我相信我一定會錯過某些明顯的東西,但我發現了各種方法來確認該子字符串包含在我正在搜索的字符串中,或者用其他東西替換它,但不返回我已經找到。返回用正則表達式發現的字符串
3
A
回答
2
CharSequence inputStr = "abbabcd";
String patternStr = "(a(b*))+(c*)";
// Compile and use regular expression
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.find();
if (matchFound)
{
// Get all groups for this match
for (int i=0; i<=matcher.groupCount(); i++)
{
String groupStr = matcher.group(i);
}
}
CharSequence是可讀的char值的等價性。該接口爲許多不同類型的字符序列提供統一的只讀訪問。 char值代表基本多語言平面(BMP)或替代品中的字符。詳情請參閱Unicode字符表示。
CharSequence
是一個接口
public interface CharSequence
7
Matcher matcher = Pattern.compile("a+").matcher("bbbbaaaaabbbb");
if(matcher.find())
System.out.println(matcher.group(0)); //aaaaa
如果你想具體部分
Matcher matcher = Pattern.compile("(a+)b*(c+)").matcher("bbbbaaaaabbbbccccbbb");
if(matcher.find()){
System.out.println(matcher.group(1)); //aaaaa
System.out.println(matcher.group(2)); //cccc
System.out.println(matcher.group(0)); //aaaaabbbbcccc
}
0組完整的模式。其他組在正則表達式(
用括號隔開+ )
B * (
C + )
並且可以單獨獲得
+0
組0表示整個模式,因此表達式「m.group(0)」等同於「m.group()」。 – 2017-10-11 16:53:17
1
import java.util.regex.*;
class Reg
{
public static void main(String [] args)
{
Pattern p = Pattern.compile("ab");
Matcher m = p.matcher("abcabd");
System.out.println("Pattern is " + m.pattern());
while(m.find())
{
System.out.println(m.start() + " " + m.group());
// m.start() will give the index and m.group() will give the substring
}
}
}
相關問題
- 1. 正則表達式返回null與返回空字符串
- 2. 蒙戈通過正則表達式發現:只返回匹配的字符串
- 3. 使用Perl返回子字符串正則表達式
- 4. 使用正則表達式匹配字符串返回null
- 5. 正則表達式的正則表達式的Java字符串
- 6. Python的正則表達式從以下字符串返回AM
- 7. 返回與正則表達式匹配的字符串
- 8. Python的正則表達式得到從字符串返回值
- 9. 返回空字符串的正則表達式
- 10. jQuery的正則表達式匹配返回空字符串
- 11. Python:返回正則表達式之間的字符串
- 12. JavaScript只返回字符串中的正則表達式
- 13. 正則表達式(正則表達式)的子字符串
- 14. C#正則表達式匹配的子表達式返回空字符串
- 15. 字符串使用正則表達式替換正則表達式字符類
- 16. MySQL正則表達式返回字符串而不是Y/N
- 17. 搜索正則表達式,返回字符串與空格
- 18. 正則表達式:返回ini節作爲字符串
- 19. 正則表達式在Javascript中返回原始字符串
- 20. 正則表達式在搜索字符串時返回空值
- 21. 正則表達式 - 返回一個字符串
- 22. 正則表達式返回空字符串
- 23. 轉換正則表達式返回字符串
- 24. 正則表達式只返回一個字符串
- 25. 正則表達式匹配,返回字符串剩餘部分
- 26. 替換字符串正則表達式返回更換兩次
- 27. 正則表達式在JavaScript字符串中返回undefined
- 28. 貓鼬不返回正則表達式子字符串
- 29. 如何處理正則表達式返回字符串?
- 30. 正則表達式正則表達式匹配字符串
請告訴我們一些實際EXA代表你的意思的mples。否則,你可能會得到你可能不想要的意外答案。 – Lion 2012-01-06 01:14:59