Java regex split double from string

ε祈祈猫儿з 提交于 2019-12-11 09:52:27

问题


I am having a problem splitting something like the following string:

43.80USD

What I want is to be able to split the expression into an array that has "43.80" as the first element and "USD" as the second. So the result would be something like:

["43.80", "USD"]

I am sure there is some way to do this with regex, but I am not proficient enough with it to figure it out on my own. Any help would be much appreciated.


回答1:


If the format of your string is fixed you can split it as follows

String[] currency = "48.50USD".split("(?<=\\d)(?=[a-zA-Z])");
System.out.println("Amount='"+currency[0]+"'; Denomination='"+currency[1]+"'");
// prints: Amount='48.50'; Denomination='USD'

The regex above uses a positive look-behind (?<=) and a positive lookahead (?=) to find a separator (which is of zero-length here) that's preceded with a number and followed by a letter.




回答2:


If your data really looks like "43.80USD" then you can use

"43.80USD".split("(?i)(?=[a-z])",2)
  • (?=[a-z]) will split before any of a-z characters
  • (?i) will make used regex case-insensitive so it will also work for uSd
  • second argument is max size of result array, since you don't want ["43.80", "U", "S, "D"] but ["43.80", "USD"] we need to use 2.



回答3:


This regex works(\d*\.\d*)([a-zA-Z]*). Group 1 will be the amount, including the decimal. Group 2 will be the USD or other monetary name. Note that this regex only requires a decimal point, everything else is optional. So this also matches: "45123.15542ABCDEFG". Group 1 will be 45123.15542 and group 2 will be ABCDEFG. If you want more strict requirements, tell me what they are and Ill put it in. Otherwise your code will look something like:

Pattern p = Pattern.compile("(\\d*\\.\\d*)([a-zA-Z]*)");//Note the double \\ to escape twice.
Matcher m = p.matcher("43.80USD");
String amount, type;
if(m.matches){
    amount = m.group(1);
    type = m.group(2);
}


来源:https://stackoverflow.com/questions/17173551/java-regex-split-double-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!