我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:

part1 = "004";
part2 = "034556";

这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。

我还想检查字符串中是否有“-”。


当前回答

使用模式是Java 8。下面是路!!

package com.company;

import java.util.regex.Pattern;

public class umeshtest {

    public static void main(String a[]) {
        String ss = "I'm Testing and testing the new feature";
        Pattern.compile(" ").splitAsStream(ss).forEach(s -> System.out.println(s));
    }
}

其他回答

// This leaves the regexes issue out of question
// But we must remember that each character in the Delimiter String is treated
// like a single delimiter        

public static String[] SplitUsingTokenizer(String subject, String delimiters) {
   StringTokenizer strTkn = new StringTokenizer(subject, delimiters);
   ArrayList<String> arrLis = new ArrayList<String>(subject.length());

   while(strTkn.hasMoreTokens())
      arrLis.add(strTkn.nextToken());

   return arrLis.toArray(new String[0]);
}

有时,如果您想拆分包含+的字符串,那么它不会拆分;相反,您将得到一个运行时错误。在这种情况下,首先将+替换为_,然后拆分:

 this.text=text.replace("/", "_");
            String temp[]=text.split("_");

我使用了一个名为stringValue的字符串,它的形式类似于“那些有硬币的人,在雨中享受,那些有钞票的人正忙着寻找避难所”。

我将使用“,”作为冒号拆分stringValue。

然后,我只想使用三个不同TextView的SetText()来显示该字符串。

String stringValue = "Those who had coins, enjoyed in the rain, those who had notes were busy looking for the shelter";
String ValueSplitByColon[] = stringValue.split(",");

String firstValue = ValueSplitByColon[0];
String secondValue = ValueSplitByColon[1];
String thirdValue = ValueSplitByColon[2];

txtV1.setText(firstValue);
txtV2.setText(secondValue;
txtV3.setText(thirdValue;

其输出如下:

txtV1值是:那些有硬币的人txtV2值为:在雨中享受txtV3值是:那些有笔记的人正忙着寻找避难所

直接处理字符串的另一种方法是将正则表达式与捕获组一起使用。这样做的优点是,它可以直接暗示对输入的更复杂的约束。例如,以下命令将字符串拆分为两部分,并确保两者仅由数字组成:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

class SplitExample
{
    private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");

    public static void checkString(String s)
    {
        Matcher m = twopart.matcher(s);
        if (m.matches()) {
            System.out.println(s + " matches; first part is " + m.group(1) +
                               ", second part is " + m.group(2) + ".");
        } else {
            System.out.println(s + " does not match.");
        }
    }

    public static void main(String[] args) {
        checkString("123-4567");
        checkString("foo-bar");
        checkString("123-");
        checkString("-4567");
        checkString("123-4567-890");
    }
}

由于模式在本例中是固定的,因此可以预先编译并存储为静态成员(在示例中是在类加载时初始化的)。正则表达式为:

(\d+)-(\d+)

括号表示捕获组;可以通过Match.group()方法访问与正则表达式的该部分匹配的字符串,如图所示。\d匹配一个十进制数字,+表示“匹配一个或多个前一个表达式)。-没有特殊含义,因此只匹配输入中的字符。请注意,当将其写成Java字符串时,需要对反斜杠进行双转义。其他一些示例:

([A-Z]+)-([A-Z]+)          // Each part consists of only capital letters 
([^-]+)-([^-]+)            // Each part consists of characters other than -
([A-Z]{2})-(\d+)           // The first part is exactly two capital letters,
                           // the second consists of digits

对于简单的用例,String.split()应该完成这项工作。如果您使用番石榴,还有一个Splitter类,它允许链接不同的字符串操作并支持CharMatcher:

Splitter.on('-')
       .trimResults()
       .omitEmptyStrings()
       .split(string);