用'*'字符替换字符串中的所有字符

时间:2015-10-04 23:03:56

标签: regex vb.net string

我到处搜索,找不到答案,如果我错了请指导我发帖,否则这是我的问题:

我想将一个字符串(例如“密码”)替换为所有'*',但它仍然具有字符串中包含的字符数,例如“password”有8个字符,所以它会替换它这个“********”而不是密码或任何其他字符串(例如“word”&gt;“****”,“string”&gt;“******”)。< / p>

如果有人能在这里帮助我,那就太棒了,谢谢!

2 个答案:

答案 0 :(得分:3)

您可以这样做:

Error initializing the application: Cannot invoke method encodePassword() on null object

此函数使用'*'字符创建一个新字符串,但其长度与输入字符串相同。

你可以像这样使用它:

class BootStrap {

    def init = { servletContext ->
        def springSecurityService
        def userRole = SecurityRole.findByAuthority("ROLE_USER") ?: new SecurityRole(authority:"ROLE_USER").save(flush:true)
        def adminRole = SecurityRole.findByAuthority("ROLE_ADMIN") ?: new SecurityRole(authority:"ROLE_ADMIN").save(flush:true)

        def user = new User(username:"user" ,password:springSecurityService.encodePassword("123"),enable:true ).save(flush:true)
        def admin = new User(username:"admin" ,password:springSecurityService.encodePassword("1234"),enable:true ).save(flush:true)
        SecurityUserSecurityRole.create(user, userRole)
        SecurityUserSecurityRole.create(admin, adminRole)
    }
    def destroy = {
    }
}

答案 1 :(得分:0)

使用regex.replace()方法:

RegularExpressions.Regex.Replace("password", "[a-zA-Z]", "*")

您可以创建如下所示的功能

 Private Function strReplace(ByVal str As String, ByVal char2replace As String)
     Dim lstr As String = Trim(str)
     str = RegularExpressions.Regex.Replace(lstr, "[a-zA-Z]", char2replace)
    'or you can use 
    'str = Regex.Replace(lstr, "[a-zA-Z]", char2replace)
    'but in this case you need to import System.Text.RegularExpressions
     Return lstr
 End Function

用法:

Dim str As String = " PassWORD "
str = strReplace(str, "*")
'Output : ********
Dim str As String = "password"
str = strReplace(str, "#")
'Output : ########
相关问题