简体   繁体   中英

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.

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

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)", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM