我有以下字符串得到字符串的Java摆脱任何外支架
34rf;43jh<helloworld>guge73g34/
我基本上要的“<”和“>”从字符串,使其返回除去外面的一切:
<helloworld>
我该怎么做?
我有以下字符串得到字符串的Java摆脱任何外支架
34rf;43jh<helloworld>guge73g34/
我基本上要的“<”和“>”从字符串,使其返回除去外面的一切:
<helloworld>
我该怎么做?
如果你只有一个“<”和一个“>”您可以使用String.split()方法,像这样:
String myWord = myWord.split("<")[1];
myWord = myWord.split(">")[0];
myWord = "<" + myWord + ">";
我有几个建议,我可能会做这样的事情这
public static String parse(String in) {
// Find the open '<'.
int p1 = in.indexOf('<');
// If we found an open less-then, check for next closing greater-then
int p2 = (p1 < 0) ? -1 : in.indexOf('>', p1 + 1);
if (p2 >= 0) {
// Found it... return the sub-string.
return in.substring(p1, p2 + 1);
}
// return the input? might want "" instead.
return in;
}
使用正则表达式:
String str = "34rf;43jh<helloworld>guge73g34/";
Pattern bracketPattern = Pattern.compile("<(.*?)>");
Matcher m = bracketPattern.matcher(str);
if (m.find())
String match = m.group(1);
这比其他人好得多。 +1 – Sinkingpoint
哦,你有无数的方法来实现这个..这是实现你所需要的一种方式。
String input = "34rf;43jh<helloworld>guge73g34/";
int start = input.indexOf('<');
int end = input.indexOf('>');
System.out.println(input.substring(start, end+1));
这是使用正则表达式实现方法以及使用replaceFirst方法的另一种方式
System.out.println(input.replaceFirst(".*<", "<").replaceFirst(">.*", ">"));
不过,如果你有一个以上的标签这两个都没有很好的候选人,你想找到所有的标签。在那里,你显然必须去正则表达式,并使用它可以找到所有的标签。下面的答案之一已经显示如何做到这一点,所以我没有这样做。
这里基本上有两个目标。
1)找到每个括号的索引。 Cosider以下代码:
static String input = "34rf;43jh<helloworld>guge73g34/";
int firstBracketPosition = 0;
int lastBracketPosition = 0;
firstBracketPosition = input.indexOf("<");
lastBracketPosition = input.lastIndexOf(">");
前三行是变量声明。第四行发现第一次出现“<”,并返回索引。第五行查找“>”的最终出现次数并返回索引。这些指数存储在它们各自的变量中。
2)你想抓住两个括号之间的文本。 (包括括号)。 考虑下面的代码:
static String output = "";
output = input.substring(firstBracketPosition, lastBracketPosition + 1);
System.out.println(output);
的第一行是一个变量声明。第二行取两个括号索引之间的输入字符串部分,将最后一个括号添加到最终位置以在输出字符串中包含最后一个括号。最后一行输出的值为output
。
使用您提供的代码,这个程序打印
<helloworld>
你告诉我们,你如何能做到这一点。 –
我试图采取索引“<" and ">”,例如x.substring(frame.indexOf(“<”)); x.substring(frame.indexOf(“>”));但那只是返回了我不想要的随机字符 – user2863323
您是否保证在输入中只有一个“<" and ">”? – rajneesh2k10