简体   繁体   English

如何使用正则表达式或子字符串从字符串中提取文本?

[英]How can I extract text from a string using regex or substring?

What I'm doing now is this:我现在正在做的是:

if (textforspeech.contains("upload completed"))
                                {
                                    String varr = textforspeech.substring(17,3);
                                    String varr1 = textforspeech.substring(0, 16);
                                    String varr2 = textforspeech.substring(21);

But my program crash on the first substring 17,3但是我的程序在第一个子串 17,3 上崩溃了

The text in the textforspeech is: "upload completed 100 0" The number 100 present percentages and will be all the time 100. And the number 0 present seconds it can be changed sometimes 0 sometimes 1 and sometimes 34.5 textforspeech中的textforspeech是:“上传完成 100 0” 数字 100 表示百分比,并且始终为 100。而数字 0 表示的秒数有时可以更改为 0 有时为 1 有时为 34.5

In varr I need to put the 100 as string "100"varr我需要将 100 作为字符串“100”
In varr1 "upload completed"varr1 “上传完成”
in varr2 "0"varr2 "0"

Only varr2 might be change in the next times could be "1" or "45.5" Before I added the seconds to the string textforspeech it was only:只有varr2可能在下一次更改可能是“1”或“45.5” 在我将秒添加到字符串textforspeech它只是:

"upload completed 100" so I could make substring(17) and substring(0,16) But now I added the seconds after the 100 so how can extract it all to the three vars ? “上传完成 100”所以我可以制作substring(17)substring(0,16)但是现在我在 100 之后添加了秒数,所以如何将它全部提取到三个变量中?

You can do something like this:你可以这样做:

string[] parts = textforspeech.split(new char[] { ' ' });

string varr = parts[2]; // "100"
string varr1 = string.format("{0} {1}", parts[0], parts[1]);  // "upload completed"
string varr2 = parts[3]; // value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM