regex - 用于自定义解析的正则表达式

标签 regex

正则表达式不是我的强项。假设我需要一个用于字符串的自定义解析器,该解析器会去除所有字母,多个小数点和字母的字符串。

例如,输入字符串为“--1-2.3-gf5.47”,解析器将返回
“-12.3547”。
我只能想出这样的变化:

string.replaceAll("[^(\\-?)(\\.?)(\\d+)]", "")

它删除了字母,但保留了其他所有内容。有指针吗?

更多示例:
输入:-34.le.78-90
输出:-34.7890

输入:df56hfp.78
输出:56.78

一些规则:
  • 仅考虑第一个数字之前的第一个负号,其他所有内容都可以忽略。
  • 我正在尝试使用Java来做到这一点。
  • 假定-ve符号(如果有)将始终出现在
    小数点。
  • 最佳答案

    刚刚在ideone上进行了测试,它似乎可以工作。这些注释应该足以解释代码。您可以将其复制/粘贴到Ideone.com中,并根据需要进行测试。

    可能可以为它编写一个正则表达式模式,但是最好实现以下类似的更简单/可读性更好的方法。

    您给出的三个示例可以打印出来:

    --1-2.3-gf5.47   ->   -12.3547
    -34.le.78-90     ->   -34.7890
    df56hfp.78       ->    56.78
    
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            System.out.println(strip_and_parse("--1-2.3-gf5.47"));
            System.out.println(strip_and_parse("-34.le.78-90"));
            System.out.println(strip_and_parse("df56hfp.78"));
        }
    
        public static String strip_and_parse(String input)
        {
            //remove anything not a period or digit (including hyphens) for output string
            String output = input.replaceAll("[^\\.\\d]", "");
    
            //add a hyphen to the beginning of 'out' if the original string started with one
            if (input.startsWith("-"))
            {
                output = "-" + output;
            }
    
            //if the string contains a decimal point, remove all but the first one by splitting
            //the output string into two strings and removing all the decimal points from the
            //second half           
            if (output.indexOf(".") != -1)
            {
                output = output.substring(0, output.indexOf(".") + 1) 
                       + output.substring(output.indexOf(".") + 1, output.length()).replaceAll("[^\\d]", "");
            }
    
            return output;
        }
    }
    

    关于regex - 用于自定义解析的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31709312/

    相关文章:

    regex - 如何组合正则表达式环视表达式

    匹配 PowerShell 代码中的 "here strings"的正则表达式

    r - 如何在 R 中使用正则表达式匹配并包含条件?

    jquery - 识别http链接并创建 anchor 标记

    python - python 正则表达式中的负前瞻问题

    javascript - 解析 YouTube URL

    c# - 正则表达式匹配字符串中的 "time"值

    c# - 快速正则表达式在我的代码中引入 C# 6 的名称 of(x) 而不是字符串文字

    ruby - 在匹配特定条件时拆分字符串

    Python:匹配包含正则表达式代码的两个变量的或