从java中的字符串中获取元素的快速方法 [英] fast way to get an element from a string in java
问题描述
我试图从我的字符串中获取一个元素,我已经从 JList 中获得了一个 getSelectedValue().toString
.它返回 [1] testString
I am trying to get an element from my string wich I have attained thtough a getSelectedValue().toString
from a JList.
It returns [1] testString
我想要做的只是从字符串中获取 1.有没有办法只从字符串中获取该元素或从字符串中删除所有其他元素?
What I am trying to do it only get the 1 from the string. Is there a way to only get that element from the string or remove all else from the string?
我试过了:
String longstring = Customer_list.getSelectedValue().toString();
int index = shortstring.indexOf(']');
String firstPart = myStr.substring(0, index);
推荐答案
你有很多方法可以做到,例如
You have many ways to do it, for example
- 正则表达式
String#replaceAll
String#substring
请参阅下面的代码以使用所有方法.
See below code to use all methods.
import java.util.*;
import java.lang.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Test {
public static void main(String args[]) {
String[] data = { "[1] test", " [2] [3] text ", " just some text " };
for (String s : data) {
String r0 = null;
Matcher matcher = Pattern.compile("\\[(.*?)\\]").matcher(s);
if (matcher.find()) {
r0 = matcher.group(1);
}
System.out.print(r0 + " ");
}
System.out.println();
for (String s : data) {
String r1 = null;
r1 = s.replaceAll(".*\\[|\\].*", "");
System.out.print(r1 + " ");
}
System.out.println();
for (String s : data) {
String r2 = null;
int i = s.indexOf("[");
int j = s.indexOf("]");
if (i != -1 && j != -1) {
r2 = s.substring(i + 1, j);
}
System.out.print(r2 + " ");
}
System.out.println();
}
}
但是结果可能会有所不同,例如 String#replaceAll
会在输入不是您期望的结果时给您错误的结果.
However results may vary, for example String#replaceAll
will give you wrong results when input is not what you expecting.
1 2 null
1 3 只是一些文字
1 2 null
这篇关于从java中的字符串中获取元素的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!