2015-07-10 163 views
2

獲取用戶名=「testuserMM」我想這正則表達式來捕獲用戶名正則表達式從字符串

highs\(\d+\)\[.*?\]\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]\sftid\(\d+\):\s. 

它沒有工作。

<55>Mar 17 12:02:00 forcesss-off [Father][1x91422234][eee][hote] abcd(QlidcxpOulqsf): highs(23455814)[mothers][192.192.21.12] ftid(64322816): oops authentication failed with (http-commo-auth, username='testuserMM' password='********'congratulation-fakem='login') 

回答

1

您可以使用一個更簡單的正則表達式:

\busername='([^']+) 

demo,結果是1組

正則表達式

  • \b - 字邊界
  • username=' - 文字字符串username='
  • ([^']+) - 包含我們的子字符串的捕獲組,其中只包含一個或多個符號,而不包含單個撇號。

UPDATE

這裏有2種方式來獲得你正在尋找的文字:

String str = "<55>Mar 17 12:02:00 forcesss-off [Father][1x91422234][eee][hote] abcd(QlidcxpOulqsf): highs(23455814)[mothers][192.192.21.12] ftid(64322816): oops authentication failed with (http-commo-auth, username='testuserMM' password='********'congratulation-fakem='login')"; 
String res = str.replaceAll(".*\\busername='([^']+)'.*", "$1"); 
System.out.println(res); 

String rx = "(?<=\\busername=')[^']+"; 
Pattern ptrn = Pattern.compile(rx); 
Matcher m = ptrn.matcher(str); 
while (m.find()) { 
    System.out.println(m.group()); 
} 

IDEONE demo

+0

它是否適合你?如果您使用的是支持它的引擎,您也可以嘗試使用lookbehind:'(?<= \ busername =')[^'] +'。 –

+0

我只在'testuserMM'的單撇號中尋找值。你的正則表達式給了我全部的價值,如用戶名='testuserMM' – user3438838

+0

你在我以前的評論中嘗試了一個向後看嗎?它會爲你贏得整個比賽的價值。 –