2015-07-10 162 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

你在我以前的评论中尝试了一个向后看吗?它会为你赢得整个比赛的价值。 –