优先考虑实际正则表达式

时间:2016-04-28 14:57:31

标签: java regex

我正在寻找能够剥夺所有' a'输入单词开头的字符(仅包含英文字母)。

如何使用正则表达式执行此操作?

以下基于正则表达式的外观未能完成这项工作:

(?<=a*?)(\w)+

对于输入abc,上述正则表达式将返回abc

使用lookbehinds有一种干净的方法吗?

一个有效的(暴力)正则表达式使用否定:

(?<=a*)([[^a]&&\w])*

为输入字bc返回abc的正确答案。

但是我想知道是否可以使用正确的quantifier更优雅的正则表达式?

4 个答案:

答案 0 :(得分:0)

Pattern removeWords = Pattern.compile("\\b(?:a)\\b\\s*", Pattern.CASE_INSENSITIVE);
Matcher fix = removeWords.matcher(YourWord);
String fixedString = fix.replaceAll("");

这会从当前字符串中删除 a ,如果您要删除其他一些字母

Pattern removeWords = Pattern.compile("\\b(?:a|b|c)\\b\\s*",Pattern.CASE_INSENSITIVE); 
你可以这样做吗

答案 1 :(得分:0)

我认为这个问题的正则表达式是过度的。

你可以这样做:

str = str.startsWith("a") ? str.substring(1) : str;

答案 2 :(得分:0)

有更简单的方法可以做到这一点,但是当你坚持使用lookbehinds时,我会给出一个。正则表达式将是

(?<=\b)a+(\w*)

正则表达式细分

(?<=\b) #Find all word boundaries
a+ #Match the character a literally at least once. We have already ensured using word boundary to find those a's only which are starting of word
(\w*) #Find remaining characters

<强> Regex Demo

Java代码

String str = "abc cdavbvhsza aaabcd";
System.out.println(str.replaceAll("(?<=\\b)a+(\\w*)", "$1"));

<强> Ideone Demo

答案 3 :(得分:0)

尝试:

(?i)\\ba?(\\w+)\\b

并用捕获的group 1替换一个单词。 代码示例:

String word = "aWord Another";
word = word.replaceAll("(?i)\\ba?(\\w+)\\b", "$1");
System.out.println(word);

带输出:

Word nother