使用分隔符解析文本以分隔不同的参数

使用分隔符解析文本以分隔不同的参数

本文介绍了Java - 使用分隔符解析文本以分隔不同的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用多个分隔符或单个分隔符来检测和分离不同的字符串匹配?

How would you use multiple delimiters or a single delimiter to detect and separate out different string matches?

例如,我使用扫描程序解析以下字符串:

For example, I use a Scanner to parse in the following string:

我想将此字符串分开,以便按顺序确定何时创建新人当他们的年龄确定。我还需要知道年龄是多少。

I would like to separate out this string to determine, in sequence, when a new person is being created and when their age is being set. I also need to know what the age is being set to.

这些论点之间和/或任何一方都可以有任何东西(不一定必须是它们之间的空格,但需要分号)。 MrsMarple可以是任何一个词。我也希望忽略同一行上//(两个斜杠)之后的任何参数,但这是可选的。

There can be anything between and/or either side of these arguments (there doesn't necessarily have to be a space between them, but the semi-colon is required). The "MrsMarple" could be any word. I would also prefer any arguments following a "//" (two slashes) on the same line to be ignored but that's optional.

如果你能想到一个简单的替代方案使用正则表达式我非常愿意考虑它。

If you can think of a simple alternative to using regex I'm more than willing to consider it.

推荐答案

我可能尝试一种简单的分割/循环方法。

I might try a simple split/loop approach.

给定字符串输入=MrsMarple = new Person(); MrsMarple.age = 30;

String[] noComments = input.split("//");
String[] statements = input.split(noComments[0]);
for(String statement: statements) {
    String[] varValue = statement.split("=");
    ...
    // Additional MrsMarple-SmartSense Technology (tm) here...
    ...
}

明智地使用 String.trim()和/或其他简单工具。

with judicious use of String.trim() and or other simple tools.

这篇关于Java - 使用分隔符解析文本以分隔不同的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:23