2012-05-21 56 views
1

我想创建一个正则表达式来生成一个匹配并剥离$和最后两个字符,如果最后一个字符以大写字母加数字结尾。简单的正则表达式匹配

I'll strip off the $ and then an ending capital letter + number: 

$mytestA1 --> expected output: mytest 
$againD4 --> expected output: again 
$something --> expected output: something 
$name3 --> expected output: name3 // because there was no capital letter before the number digit 
$name2P4 --> expected output: name2 

我会在我的代码中检查'if'检查是否存在$,我甚至会打扰运行正则表达式。

谢谢。

+1

是太空在'我的测试'中有一个错字?另外,你使用哪种语言? – Junuxx

+0

描述有点不清楚 - 你能发布预期输出的例子 –

+0

感谢您的快速回复。我加入了预期的产出。使用Java来运行正则表达式。 –

回答

1

在Java中只使用字符串#的replaceAll:

String replaced = str.replaceAll("^\\$|[A-Z]\\d$", ""); 
+1

和测试用例在:http://www.rubular.com/r/ueBkJYVLQI – anubhava

+0

非常感谢这个答案,这是最简单的一个。 –

+0

不客气,很高兴它为你解决。 – anubhava

1

这可能不是最有效的,但它会工作...

\$([^\s]*)(?:[A-Z]\d)|\$([^\s]*) 

它的工作原理,因为第一组发现所有那些国会随后数... ...,第二个发现所有没有后缀的那些...

如果您从捕获组获得您想要的匹配项。

我觉得像这样的工作...

import java.io.Console; 
import java.util.regex.Pattern; 
import java.util.regex.Matcher; 

public class HereYouGo { 
    public static void main (String args[]) { 

     String input = "$mytestA1 --> expected output: mytest\r\n$againD4 --> expected output: again\r\n$something --> expected output: something\r\n$name3 --> expected output: name3 // because there was no capital letter before the number digit\r\n$name2P4 --> expected output: name2\r\n";  

     Pattern myPattern = Pattern.compile("\\$([^ ]*)(?:[A-Z]\\d)|\\$([^ ]*)", Pattern.DOTALL | Pattern.MULTILINE); 

     Matcher myMatcher = myPattern.matcher(input); 

     while(myMatcher.find()) 
     { 
      String group1 = myMatcher.group(1); 
      String group2 = myMatcher.group(2); 

      //note: this should probably be changed in the case neither match is found 
      System.out.println(group1!=null? group1 : group2); 
     } 
    } 
} 

这将输出以下

mytest 
again 
something 
name3 
name2 
+0

感谢您的及时回复。这个答案的问题是,如果你输入“$ name3”,它会返回“nam”,因为'e'不是大写字母,所以当我期待“名称”时。作为参考,我正在使用这个测试工具。我不确定它是否100%可靠 - http://www.regextester.com/ –

+0

我使用RegexBuddy测试并使用Java正则表达式引擎,它工作得很好。 –

+0

我认为你对...有不区分大小写; ;-) –