[英]How to delete the specific lines that starts and ends with specific string in a file in java?
[英]Check if string starts or ends with specific letter - java
我在檢查字符串中是否有字母時遇到一些問題。 現在,我遇到服務器/客戶端的情況,服務器將命令發送回客戶端。
該命令可以是:
RM20 B
RM20 L
RM20 I
RM20 A "User input"
RM20 C
我如何檢查字母是B,L,I還是A或C?
現在我做了這段代碼:
if ((fromServer.startsWith("RM20 A"))) {
else if ((fromServer.startsWith("RM20 C")))
else {
}
這有效嗎? 還是if語句和else if語句相同? 我不能使用末端為,因為RM20 A末端有很多輸入。
有沒有辦法檢查中間的東西。 當你得到時,說
“ RM20 A 123213124”作為字符串?
假設您的格式如下:
<RM Code> <Letter> <Numbers> <Anything else>
然后,您可以執行以下操作:
String[] values = input.split(" ");
if(values[1].equals("A")) {
// Code for A.
}
我只會對“ A”命令輸入使用startsWith()
測試,因為那是唯一具有任意結尾的命令。 其他命令具有確切的值,因此您應該使用equals()
測試。 這樣,您可以可靠地捕獲錯誤(例如“ RM20 B xyz”)。
static final String A_COMMAND_PREFIX = "RM20 A ";
.
.
.
if (fromServer.startsWith(A_COMMAND_PREFIX)) {
// Process user input
final String userInput = fromServer.substring(A_COMMAND_PREFIX.length());
} else if (fromServer.equals("RM20 B")) {
// Process B command
} else if (fromServer.equals("RM20 L")) {
// Process L command
} else if (fromServer.equals("RM20 I")) {
// Process I command
} else if (fromServer.equals("RM20 C")) {
// Process C command
} else {
// Handle unknown command
}
我假設您已經確定fromServer
不為null。
使用正則表達式捕獲不同的組。 String regex
表達式捕獲直到空格為止的所有單詞字符。 然后捕獲任何字母az或AZ。 然后,如果有空間和其他一些輸入,它將捕獲並使用它。
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class test {
public static void main(String ar[]) throws java.io.IOException {
String regex = "(\\w*) ([a-zA-Z])( (.*))?";
String str1 = "RM20 A";
String str2 = "RM20 B";
String str3 = "RM20 C this is a user message.";
Pattern pattern = Pattern.compile(regex);
Matcher match1 = pattern.matcher(str1);
Matcher match2 = pattern.matcher(str2);
Matcher match3 = pattern.matcher(str3);
String a;
while (match1.find()) {
a = "Group 1: " + match1.group(1) + "\nGroup 2: " + match1.group(2);
System.out.println(a);
}
System.out.println();
while (match2.find()) {
a = "Group 1: " + match2.group(1) + "\nGroup 2: " + match2.group(2);
System.out.println(a);
}
System.out.println();
while (match3.find()) {
a = "Group 1: " + match3.group(1) + "\nGroup 2: " + match3.group(2) + "\nGroup 4: " + match3.group(4);
System.out.println(a);
}
}
}
>>> Group 1: RM20
>>> Group 2: A
>>> Group 1: RM20
>>> Group 2: B
>>> Group 1: RM20
>>> Group 2: C
>>> Group 4: this is a user message.
您還可以在輸入代碼中捕獲字母/數字:
String regex = "([a-zA-Z]*)(\\d*) ([a-zA-Z])( (.*))?";
String str1 = "RM20 A message thingy";
Pattern pattern = Pattern.compile(regex);
Matcher match1 = pattern.matcher(str1);
while (match1.find()) {
System.out.println(match1.group(1));
System.out.println(match1.group(2));
System.out.println(match1.group(3));
System.out.println(match1.group(5));
}
>>> RM
>>> 20
>>> A
>>> message thingy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.