微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我可以在某些字符之间显示字符串吗?

如何解决我可以在某些字符之间显示字符串吗?

我有一个巨大的日志文件,里面有数百个异常,每个异常也有发生的时间,但它们不一定在每个异常的同一个地方(在堆栈跟踪中)。我能看到的唯一共同点是它们总是在方括号之间。

我知道日志文件中的日期总是采用 [25/05/21 10:28:41:231 BST] 的形式。有没有一种方法可以只在 List<String>显示“[]”之间的字符。或者只是在字符串上,如果我可以将其解析为字符串。我当时正在考虑编写一些逻辑来测试字符串 25/05/21 10:28:41:231 BST 是否是一个日期,以避免在括号之间有更多数据时得到不需要的结果。

到目前为止,我尝试用“[”拆分它,但遇到了一些问题。数据文件中有一些“[”,这意味着时间和日期不一定是 String 数组中的第一个输入,所以我不能全部选择它们。

任何有关如何解决此问题/其他方法的输入或建议将不胜感激!

解决方法

某种形式

"\[(\d\d/\d\d/\d\d \d\d:\d\d:\d\d:\d\d [A-Z]{3})\]"

例如在斯卡拉

scala> val pattern = "\\[(\\d\\d/\\d\\d/\\d\\d \\d\\d:\\d\\d:\\d\\d:\\d\\d\\d [A-Z]{3})\\]".r
val pattern: scala.util.matching.Regex = \[(\d\d/\d\d/\d\d \d\d:\d\d:\d\d:\d\d\d [A-Z]{3})\]

scala> pattern.matches("[25/05/21 10:28:41:231 BST]")
val res5: Boolean = true
,

您可以试试这个 getBetween() 方法。您可能会发现它对其他方面也很有用:

/**
 * Retrieves any string data located between the supplied string leftString
 * parameter and the supplied string rightString parameter.<br><br>
 * <p>
 * This method will return all instances of a substring located between the
 * supplied Left String and the supplied Right String which may be found
 * within the supplied Input String.<br>
 *
 * @param inputString (String) The string to look for substring(s) in.<br>
 *
 * @param leftString  (String) What may be to the Left side of the substring
 *                    we want within the main input string. Sometimes the
 *                    substring you want may be contained at the very
 *                    beginning of a string and therefore there is no
 *                    Left-String available. In this case you would simply
 *                    pass a Null String ("") to this parameter which
 *                    basically informs the method of this fact. Null can
 *                    not be supplied and will ultimately generate a
 *                    NullPointerException.<br>
 *
 * @param rightString (String) What may be to the Right side of the
 *                    substring we want within the main input string.
 *                    Sometimes the substring you want may be contained at
 *                    the very end of a string and therefore there is no
 *                    Right-String available. In this case you would simply
 *                    pass a Null String ("") to this parameter which
 *                    basically informs the method of this fact. Null can
 *                    not be supplied and will ultimately generate a
 *                    NullPointerException.<br>
 *
 * @param options     (Optional - Boolean - 2 Parameters):<pre>
 *
 *      ignoreLetterCase    - Default is false. This option works against the
 *                            string supplied within the leftString parameter
 *                            and the string supplied within the rightString
 *                            parameter. If set to true then letter case is
 *                            ignored when searching for strings supplied in
 *                            these two parameters. If left at default false
 *                            then letter case is not ignored.
 *
 *      trimFound           - Default is true. By default this method will trim
 *                            off leading and trailing white-spaces from found
 *                            sub-string items. General sentences which obviously
 *                            contain spaces will almost always give you a white-
 *                            space within an extracted sub-string. By setting
 *                            this parameter to false,leading and trailing white-
 *                            spaces are not trimmed off before they are placed
 *                            into the returned Array.</pre>
 *
 * @return (String[] Array) Returns a Single Dimensional String Array of all 
 *         the sub-strings found within the supplied Input String which are 
 *         between the supplied Left-String and supplied Right-String.
 */
public static String[] getBetween(String inputString,String leftString,String rightString,boolean... options) {
    // Return null if nothing was supplied.
    if (inputString.isEmpty() || (leftString.isEmpty() && rightString.isEmpty())) {
        return null;
    }

    // Prepare optional parameters if any supplied.
    // If none supplied then use Defaults...
    boolean ignoreCase = false;      // Default.
    boolean trimFound = true;        // Default.
    if (options.length > 0) {
        if (options.length >= 1) {
            ignoreCase = options[0];
            if (options.length >= 2) {
                trimFound = options[1];
            }
        }
    }

    // Remove any control characters from the
    // supplied string (if they exist).
    String modString = inputString.replaceAll("\\p{Cntrl}","");

    // Establish a List String Array Object to hold
    // our found substrings between the supplied Left
    // String and supplied Right String.
    List<String> list = new ArrayList<>();

    // Use Pattern Matching to locate our possible
    // substrings within the supplied Input String.
    String regEx = java.util.regex.Pattern.quote(leftString) + "{1,}"
            + (!rightString.isEmpty() ? "(.*?)" : "(.*)?")
            + java.util.regex.Pattern.quote(rightString);
    if (ignoreCase) {
        regEx = "(?i)" + regEx;
    }

    java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regEx);
    java.util.regex.Matcher matcher = pattern.matcher(modString);
    while (matcher.find()) {
        // Add the found substrings into the List.
        String found = matcher.group(1);
        if (trimFound) {
            found = found.trim();
        }
        list.add(found);
    }
    return list.toArray(new String[list.size()]);
}

要使用它,您可以执行以下操作:

String[] res = getBetween(logString,"[","]");
System.out.println(res[0]);

String[] parts = res[0].split("\\s+");
String date = parts[0];
String time = parts[1] + " " + parts[2];
System.out.println("Date: --> " + date);
System.out.println("Time: --> " + time);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。