用正则表达式将字符替换为数字

问题描述 投票:-3回答:1

我想将String中的字符替换为数字。例如,

Input: abcdefghia
Output: 1234567891

实际上,即使在其他语言中,也可以是任何其他字符而不是数字

所以我的想法是创建一个程序,用另一种语言将字符替换为字符。我想知道如何完成这样的任务的最佳实践。

这是我的解决方案。我们可以使用正则表达式并为每个字符创建模式,然后使用方法replaceall()替换String中的所有字符

java regex character replaceall
1个回答
1
投票

Java> 8有一个带有lambda的replaceAll:

String output = Pattern.compile("[A-z]").matcher(input)
    .replaceAll(mr -> String.valueOf((mr.group().charAt(0) % 32) % 10));

字母开始于32范围+ 1,a - > 1,...,i - > 9,j - > 0,k - > 1,...

© www.soinside.com 2019 - 2024. All rights reserved.