【发布时间】:2017-05-18 16:31:08
【问题描述】:
我使用的是 Java 8,并且有以下正则表达式:
https://regex101.com/r/XEgPWe/1
如您所见,它识别数字。
我正在尝试实现一个 Java 类,它将正则表达式匹配的值替换为“X”字符。
package com.jobs.spring.service;
public class ReplaceServiceImpl implements ReplaceService {
private static final String REGEX_NUMBERS = "/\b(?:zero|nil|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixfteen|seventeen|eighteen|nineteen|een|twee|drie|vier|fyf|ses|sewe|agt|nege|tien|iqanda|Kunye|Kubili|Kuthathu|Kune|Kuhlanu|Yisithupa|Yisikhombisa|Yisishiyagalombili|Yisishiyagalolunye|nnoto|nngwe|pedi|tharo|nne|hlano|tshelela|supa|robedi|robong|leshome|unothi|inye|zimbini|zintathu|zine|zintlanu|zintandathu|isixhenxe|sisibhozo|lithoba|cero|uno|dos|tres|cuatro|cinco|seis|siete|ocho|nueve|diez|Zéro|Un|Deux|Trois|Quatre|Cinq|Sept|Huit|Neuf|Dix|eins|zwei|drei|fünf|sechs|sieben|acht|neun|zehn|elf|[0-9])(?:.{0,10}(?:zero|nil|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|een|twee|drie|vier|fyf|ses|sewe|agt|nege|tien|iqanda|Kunye|Kubili|Kuthathu|Kune|Kuhlanu|Yisithupa|Yisikhombisa|Yisishiyagalombili|Yisishiyagalolunye|nnoto|nngwe|pedi|tharo|nne|hlano|tshelela|supa|robedi|robong|leshome|unothi|inye|zimbini|zintathu|zine|zintlanu|zintandathu|isixhenxe|sisibhozo|lithoba|cero|uno|dos|tres|cuatro|cinco|seis|siete|ocho|nueve|diez|Zéro|Un|Deux|Trois|Quatre|Cinq|Sept|Huit|Neuf|Dix|eins|zwei|drei|fünf|sechs|sieben|acht|neun|zehn|elf|[0-9])){4,}\b/gi";
@Override
public String removePII(String input) {
input = input.replaceAll(REGEX_NUMBERS, "X");
return input;
}
public static void main(String[] args) {
ReplaceService rep = new ReplaceServiceImpl();
System.out.println(rep.removePII("hello some text 1234567890 more.."));
}
}
我希望输出为:
hello some text XXXXXXXXXX more..
但它是:
hello some text 1234567890 more..
来自regex tester,我的正则表达式是正确的,所以我可能在我的 Java 中做错了什么。
欢迎任何建议。
谢谢。
【问题讨论】:
-
删除开头的
/和结尾的/gi。在开头添加(?i)。和双反斜杠。 -
您好 Wiktor Stribiżew,感谢您的建议。我尝试删除
/,但没有任何区别。 -
是的,但你也需要双反斜杠。
-
您的正则表达式使用我相信 (
/gi) 的方言,默认情况下不支持。在此处验证您的正则表达式:regexplanet.com/advanced/java/index.html -
您正在使用字符串来填充正则表达式。您需要转义
\。所以例如\d变成\\d等...