使用JavaRegexp

问题描述 投票:0回答:1
我的字符串以这种格式:

mydb://<user>:<password>@<host>:27017
我想使用Java Regexp来从字符串中提取

<user>

<password>
字符串。最好的方法是什么?

Edit:

我希望能够在字符串的替换方法中使用此REGEXP,以便我只留下相关的用户和密码字符串

您可以使用此正则(模式)

java regex
1个回答
6
投票

然后捕获第1组和#2的组将分别具有您的用户和密码。

代码:

String str = "mydb://foo:bar@localhost:27017"; Pattern p = Pattern.compile("^mydb://([^:]+):([^@]+)@[^:]+:\\d+$"); Matcher matcher = p.matcher(str); if (matcher.find()) System.out.println("User: " + matcher.group(1) + ", Password: " + matcher.group(2));

输出:

User: foo, Password: bar

Regex详细信息:

^

:开始

mydb://
    :比赛
  • mydb://
    
    
  • ([^:]+)
    :匹配除
    :
    :
  • 的任何其他字符中的1+,并在第1组组中捕获
  • :
    :匹配A
    ([^@]+)
  • @
    :匹配以外的任何字符的1+,并在第2组组中捕获
    @
  • :匹配A
  • @
    
    
    [^:]+
  • :匹配除
  • :
    
    
    :
  • :匹配A
  • :
    
    
    \\d+
  • :匹配1+数字
  • $
    :结束
    
  • Edit:
    基于您的评论:如果要使用字符串方法,则:
  • String regex = "^mydb://([^:]+):([^@]+)@[^:]+:\\d+$"; String user = str.replaceAll(regex, "$1"); String pass = str.replaceAll(regex, "$2")
  • 	
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.