簡體   English   中英

這個java正則表達式有什么問題?

[英]what is wrong with this java regex?

final static private Pattern includePattern = Pattern.compile("^\\s+([^\\s]*)");

...

Matcher mtest = includePattern.matcher("   this.txt");
String ftest = mtest.group(1);

我得到一個異常No match found at java.util.regex.Matcher.group(Matcher.java:468)

我正在尋找至少1個空格字符,然后是一組捕獲的非空格字符。 我哪里出錯了?

在使用group(...)之前,首先需要調用.find() group(...)

請注意, find()返回一個boolean ,因此安全(r)執行以下操作:

final static private Pattern includePattern = Pattern.compile("^\\s+([^\\s]*)");
Matcher mtest = includePattern.matcher("   this.txt");
String ftest = m.find() ? mtest.group(1) : null;

並且[^\\\\s]可以重寫為\\\\S (大寫s )。

你可能在你的問題中簡化了你的例子,但我假設你知道String.trim()處理任何前導和尾隨空白字符的事實。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM