String text = "/'Team1 = 6', while /'Team2 = 4', and /'Team3 = 2'";
String[] body = text.split("/|,");
String b1 = body[1];
String b2 = body[2];
String b3 = body[3];
所需结果:
b1 = 'Team1 = 6'
b2 = 'Team2 = 4'
b3 = 'Team3 = 2'
答案 0 :(得分:2)
使用正则表达式。像这样:
String text = "/'Team1 = 6', while /'Team2 = 4', and /'Team3 = 2'";
Matcher m = Pattern.compile("(\\w+\\s=\\s\\d+)").matcher(text);
// \w+ matches the team name (eg: Team1). \s=\s matches " = " and \d+ matches the score.
while (m.find()){
System.out.print(m.group(1)+"\n");
}
此打印:
Team1 = 6
Team2 = 4
Team3 = 2
答案 1 :(得分:1)
您可以通过多种方式来执行此操作,但是在您的情况下,我会使用regex。
我不懂Java,但是认为这种正则表达式模式应该可以工作:
Pattern compile("\/'(.*?)'")
具有此模式的随机正则表达式测试器站点位于:https://regex101.com/r/MCRfMm/1
答案 2 :(得分:0)
我要说“朋友不要让朋友使用正则表达式”,建议对此进行解析。内置类StreamTokenizer
将处理此作业。
private static void testTok( String in ) throws Exception {
System.out.println( "Input: " + in );
StreamTokenizer tok = new StreamTokenizer( new StringReader( in ) );
tok.resetSyntax();
tok.wordChars( 'a', 'z' );
tok.wordChars( 'A', 'Z' );
tok.wordChars( '0', '9' );
tok.whitespaceChars( 0, ' ' );
String prevToken = null;
for( int type; (type = tok.nextToken()) != StreamTokenizer.TT_EOF; ) {
// System.out.println( tokString( type ) + ": nval=" + tok.nval + ", sval=" + tok.sval );
if( type == '=' ) {
tok.nextToken();
System.out.println( prevToken + "=" + tok.sval );
}
prevToken = tok.sval;
}
}
输出:
Input: /'Team1 = 6', while /'Team2 = 4', and /'Team3 = 2'
Team1=6
Team2=4
Team3=2
BUILD SUCCESSFUL (total time: 0 seconds)
该技术的一个优点是,分别对诸如“ Team1”,“ =“和“ 6”之类的单个标记都进行了解析,而到目前为止展示的正则表达式已经很复杂,并且必须变得更加复杂。分别隔离每个令牌。
答案 3 :(得分:0)
您可以在“一个斜杠上进行分割,还可以在前面加一个逗号,后跟零个或多个非斜杠字符”:
String[] body = text.split("(?:,[^/]*)?/");
答案 4 :(得分:0)
public class MyClass {
public static void main(String args[]) {
String text = "/'Team1 = 6', while /'Team2 = 4', and /'Team3 = 2'";
char []textArr = text.toCharArray();
char st = '/';
char ed = ',';
boolean lookForEnd = false;
int st_idx =0;
for(int i =0; i < textArr.length; i++){
if(textArr[i] == st){
st_idx = i+1;
lookForEnd = true;
}
else if(lookForEnd && textArr[i] == ed){
System.out.println(text.substring(st_idx,i));
lookForEnd = false;
}
}
// we still didn't find ',' therefore print everything from lastFoundIdx of '/'
if(lookForEnd){
System.out.println(text.substring(st_idx));
}
}
}
/*
'Team1 = 6'
'Team2 = 4'
'Team3 = 2'
*/
答案 5 :(得分:0)
您可以使用split和正则表达式,使用alternation匹配字符串的开头,后跟一个正斜杠或匹配一个逗号,不匹配一个或多个逗号,然后匹配一个正斜杠,然后匹配一个肯定lookahead表示断言之后是'
(?:^/|,[^,]+/)(?=')
说明
(?:
启动非捕获组
^/
声明字符串的开头,后跟正斜杠|
或,[^,]+/
匹配一个逗号,然后使用否定的character class匹配一次或多次而不是逗号,然后匹配一个正斜杠(?=')
肯定的前瞻性断言是'
)
关闭非捕获组获取匹配而不是拆分
如果要匹配'Team1 = 6'
之类的模式,可以使用:
'[^=]+=[^']+'