Android/Java Regex to remove extra zeros from sub-strings

前端 未结 7 1343
闹比i
闹比i 2020-12-16 17:04

I have the following string as input :

\"2.0,3.00,-4.0,0.00,-0.00,0.03,2.01,0.001,-0.03,101\"

Final output will be like :

         


        
7条回答
  •  天涯浪人
    2020-12-16 17:40

    UPDATE to cover more cases such as 01.,.100, 01.10

    (?<=,|^)(?:[0.+-]+(?=0(?:,|\.\B|$))|0+(?=[1-9]))|\.0+\b|\b0+(?=\d*\.\b)|\.\B|(?<=[1-9])0+(?=,|$)
    

    This pattern requires more backtracking, thus can get slower on large input. Java String:

    "(?<=,|^)(?:[0.+-]+(?=0(?:,|\\.\\B|$))|0+(?=[1-9]))|\\.0+\\b|\\b0+(?=\\d*\\.\\b)|\\.\\B|(?<=[1-9])0+(?=,|$)"
    

    In addition to the previous pattern this one matches

    • (?<=,|^)(?:...|0+(?=[1-9])) add leading zeros preceding [1-9]
    • \.0+\b modified to match period with zeros only before a word boundary
    • \b0+(?=\d*\.\b) match zeros at boundary if period preceded by optional digits ahead
    • \.\B matches a period bordering to a non word boundary (eg .,)
    • (?<=[1-9])0+(?=,|$) matches trailing zeros following [1-9]

    Demo at regex101 or Regexplanet (click Java)


    Answer before update
    You can also try replaceAll this regex with empty.

    (?<=,|^)[0.+-]+(?=0(?:,|$))|\.0+\b|\b0+(?=\.)
    
    • (?<=,|^)[0.+-]+(?=0(?:,|$)) matches all parts that consist only of [0.+-] with at least a trailing zero. Limited by use of lookaround assertions: (?<=,|^) and (?=0(?:,|$))

    • |\.0+\b or match a period followed by one or more zeros and a word boundary.

    • |\b0+(?=\.) or match a boundary followed by one or more zeros if a period is ahead.

    Unquestioned cases like 0.,01,1.10 are not covered by this pattern yet. As a Java String:

    "(?<=,|^)[0.+-]+(?=0(?:,|$))|\\.0+\\b|\\b0+(?=\\.)"
    

    Demo at regex101 or Regexplanet (click Java)

提交回复
热议问题