从一系列字符中的第一次出现字符之后检索字符串的子字符串。

huangapple go评论110阅读模式
英文:

Retrieve a Sub-string from a string after the first occurrence of a character from a range of characters

问题

我正试图从字符串中检索子字符串,从第一个出现在 A 到 Z 和 a 到 z 之间的任何字符开始。

例如:

如果字符串是 13BHO1234FO

那么子字符串应该是 BHO1234FO

即从字符 'B' 第一次出现的位置开始的字符串。

英文:

i am trying to retrieve a sub-string from a string from the first occurence of any character between A-Z and a-z

for example:

if the string is 13BHO1234FO

then substring should be BHO1234FO

i.e the string from the first occurence of the character 'B'.

答案1

得分: 1

尝试这个。它只是删除你不想要的字符串的第一部分,并返回剩下的部分。原始字符串保持不变。

String[] testCases =
        { "13BHO1234FO", "ARSTOP123!", "133KSLK", "122222" };

for (String s : testCases) {
    String sub = s.replaceFirst("^[^A-Za-z]+", "");
    System.out.println("'" + sub + "'");
}

打印被单引号包围的子字符串以显示字符串。

'BHO1234FO'
'ARSTOP123!'
'KSLK'
''
英文:

Try this. It simply deletes the first part of the string you don't want and returns the rest. The original string is unchanged.

String[] testCases =
		{ "13BHO1234FO", "ARSTOP123!", "133KSLK", "122222" };

for (String s : testCases) {
	String sub = s.replaceFirst("^[^A-Za-z]+", "");
	System.out.println("'" + sub + "'");
}

Prints substrings surrounded by single quotes to show the string.

'BHO1234FO'
'ARSTOP123!'
'KSLK'
''

答案2

得分: 0

你可以使用 regexMatcher 来查找第一个字母字符的索引,然后从该索引开始创建一个 substring

import java.util.regex.*;
class Main {
    public static void main(String[] args) {
        String text = "13BHO1234FO";
        Pattern pattern = Pattern.compile("[A-Za-z]");
        Matcher matcher = pattern.matcher(text);
        matcher.find();
        int index = matcher.start();
        String substr = text.substring(index);
        System.out.println(substr);
    }
}
英文:

You can use a regex and Matcher to find the index of the first alphabetical character and make a substring starting from the index:

import java.util.regex.*;
class Main {
    public static void main(String[] args) {
        String text = "13BHO1234FO";
        Pattern pattern = Pattern.compile("[A-Za-z]");
        Matcher matcher = pattern.matcher(text);
        matcher.find();
        int index = matcher.start();
        String substr = text.substring(index);
        System.out.println(substr);
    }
}

答案3

得分: 0

public static void main(String[] args) {
    String test = "13BHO1234FO";
    System.out.println(test.replaceFirst("^.*?(?=[A-Za-z])", ""));
}
英文:

Try this one:

public static void main(String[] args) {
    String test = "13BHO1234FO";
    System.out.println(test.replaceFirst("^.*?(?=[A-Za-z])", ""));
}

huangapple
  • 本文由 发表于 2020年7月30日 06:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63163298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定