在 Java 中查找一个正则表达式来分隔表示复数的字符串。代码示例会很棒。输入字符串的格式为:
"a+bi"
Example: "300+400i", "4+2i", "5000+324i".
我需要从字符串中检索 300 和 400。
我知道我们可以用这种方式粗暴地做到这一点。
str.substring(0, str.indexOf('+'));
str.substring(str.indexOf('+')+1,str.indexOf("i"));
我需要从字符串中检索 300 和 400。
使用String.split(regex)
函数怎么样:
String s[] = "300-400i".split("[\Q+-\Ei]");
System.out.println(s[0]+" "+s[1]); //prints 300 400
匹配的正则表达式是:/[0-9]{1,}[+-][0-9]{1,}i/
您可以使用此方法:
Pattern complexNumberPattern = Pattern.compile("[0-9]{1,}");
Matcher complexNumberMatcher = complexNumberPattern.matcher(myString);
并在complexNumberMatcher
上使用find
和group
方法来检索myString
使用这个:
[0-9]{1,}
它将返回数字。
希望对您有所帮助。
正则表达式
([-+]?d+.?d*|[-+]?d*.?d+)s*+s*([-+]?d+.?d*|[-+]?d*.?d+)i
示例正则表达式
http://rubular.com/r/FfOAt1zk0v
示例爪哇
string regexPattern =
// Match any float, negative or positive, group it
@"([-+]?d+.?d*|[-+]?d*.?d+)" +
// ... possibly following that with whitespace
@"s*" +
// ... followed by a plus
@"+" +
// and possibly more whitespace:
@"s*" +
// Match any other float, and save it
@"([-+]?d+.?d*|[-+]?d*.?d+)" +
// ... followed by 'i'
@"i";
Regex regex = new Regex(regexPattern);
Console.WriteLine("Regex used: " + regex);
while (true)
{
Console.WriteLine("Write a number: ");
string imgNumber = Console.ReadLine();
Match match = regex.Match(imgNumber);
double real = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
double img = double.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture);
Console.WriteLine("RealPart={0};Imaginary part={1}", real, img);
}
试试这个。至于我,它有效。
public static void main(String[] args) {
String[] attempts = new String[]{"300+400i", "4i+2", "5000-324i", "555", "2i", "+400", "-i"};
for (String s : attempts) {
System.out.println("Parsingt" + s);
printComplex(s);
}
}
static void printComplex(String in) {
String[] parts = in.split("[+-]");
int re = 0, im = 0, pos = -1;
for (String s : parts) {
if (pos != -1) {
s = in.charAt(pos) + s;
} else {
pos = 0;
if ("".equals(s)) {
continue;
}
}
pos += s.length();
if (s.lastIndexOf('i') == -1) {
if (!"+".equals(s) && !"-".equals(s)) {
re += Integer.parseInt(s);
}
} else {
s = s.replace("i", "");
if ("+".equals(s)) {
im++;
} else if ("-".equals(s)) {
im--;
} else {
im += Integer.parseInt(s);
}
}
}
System.out.println("Re:t" + re + "nIm:t" + im);
}
输出:
Parsing 300+400i
Re: 300
Im: 400
Parsing 4i+2
Re: 2
Im: 4
Parsing 5000-324i
Re: 5000
Im: -324
Parsing 555
Re: 555
Im: 0
Parsing 2i
Re: 0
Im: 2
理论上你可以使用这样的东西:
Pattern complexNumberPattern = Pattern.compile("(.*)+(.*)");
Matcher complexNumberMatcher = complexNumberPattern.matcher(myString);
if (complexNumberMatcher.matches()) {
String prePlus = complexNumberMatcher.group(1);
String postPlus = complexNumberMatcher.group(2);
}
与选择数字相比,这给您带来的优势在于,它允许您阅读以下内容:5b+17c 作为 5b 和 17c
编辑:刚刚注意到你不想要这些字母,所以没关系,但这将使你更好地控制它,以防其他字母出现在其中。