[英]Using regex in java to remove a dollar sign and comma from a currency field within a field in a column delimited file
I am having a bit of a challenge trying to remove the dollar sign and thousands separator (comma in my case) from a currency field that resides on a record in a comma delimited file using the string.replaceAll command. 我试图从使用string.replaceAll命令驻留在逗号分隔文件中的记录上的货币字段中删除美元符号和千位分隔符(在我的情况下为逗号)时遇到一些挑战。
Removing the dollar sign and comma (all commas) is no problem, but the comma field delimiters need to stay and here lies my challenge. 删除美元符号和逗号(所有逗号)都没有问题,但是逗号字段分隔符需要保留,这就是我的挑战。 I have spend a bit of time researching this and am spinning my wheels.
我花了一点时间研究这个并且正在旋转我的车轮。
Below is a pattern for the type of record being read in and what I would like to look like after. 下面是读入记录类型的模式以及我希望看到的内容。
Before - fieldA, fieldB, fieldC, $1,000.00, fieldD, FieldE
之前 -
fieldA, fieldB, fieldC, $1,000.00, fieldD, FieldE
After - fieldA, fieldB, fieldC, 1000.00, fieldD, fieldE
After-
fieldA, fieldB, fieldC, 1000.00, fieldD, fieldE
Or would I be better off not using a regex pattern? 或者我最好不使用正则表达式模式?
Any help is greatly appreciated. 任何帮助是极大的赞赏。
Notice the difference between the commas you want to remove and the ones you don't. 请注意您要删除的逗号与不删除的逗号之间的区别。 The field seprator is always followed by a space, so use the following regex:
字段分隔符后面跟一个空格,所以使用以下正则表达式:
String.replaceAll(",[^ ]", "");
The regex ,[^ ]
means "comma, followed by something that is not a space". 正则表达式
,[^ ]
表示“逗号,后跟不是空格的东西”。 To replace the dollar sign, you should probably escape it since it has special meaning for regex: 要替换美元符号,您应该逃避它,因为它对正则表达式有特殊意义:
String.replaceAll("\\$", "");
You can use: 您可以使用:
String repl = str.replaceAll("(?<=\\d),(?=\\d)|\\$", "");
//=> fieldA, fieldB, fieldC, 1000.00, fieldD, FieldE
尝试这个
s = s.replaceAll("\\$|(?<=\\d),(?=\\d)", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.