[英]Looking for A Regular expression to match java regex (punct) pattern
我正在尋找一個正則表達式的幫助/支持,它將匹配 class 下面的 studentIdMatch2 值。 studentIdMatch1 匹配得很好。但是 studentIdMatch2 有 studentId,它可以允許除:和 ^ 和逗號以外的所有特殊字符。因此它不起作用,感謝您的時間並感謝您的支持。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegEx {
public static void main(String args[]){
String studentIdMatch1 = "studentName:harry,^studentId:Id123";
String studentIdMatch2 = "studentName:harry,^studentId:Id-H/MPU/L&T/OA+_T/(1490)/17@)123";
Pattern pattern = Pattern
.compile("(\\p{Punct}?)(\\w+?)(:)(\\p{Punct}?)(\\w+?)(\\p{Punct}?),");
Matcher matcher = pattern.matcher(studentIdMatch1 + ","); // Works Fine(Matches Student Name and Id)
// No Special Characters in StudentId
//Matcher matcher = pattern.matcher(studentIdMatch2 + ","); //Wont work Special Characters in StudentId. Matches Student Name
while (matcher.find()) {
System.out.println("group1 = "+matcher.group(1)+ "group2 = "+matcher.group(2) +"group3 = "+matcher.group(3) +"group4 = "+matcher.group(4)+"group5 = "+matcher.group(5));
}
System.out.println("match ended");
}
}
你可以試試:
^SutdentName:(\w+),\^StudenId:([^\s,^:]+)$
上述正則表達式的解釋:
^, $
- 分別代表行的開始和結束。SutdentName:
- 匹配SutdentName:
字面意思。 雖然在我看來它應該是 StudentName; 但我沒有改變它。(\w+)
- 表示第一個捕獲組僅匹配單詞字符,即[A-Za-z0-9_]
一次或多次greedily 。,\^StudenId:
- 匹配,^StudenId
字面意思。 這里我也猜應該是StudentId。([^\s,^:]+)
- 表示第二個捕獲組匹配除空格、 ,
、 ^
和:
一次或多次greedily之外的所有內容。 您可以根據自己的要求添加其他人。您可以在此處找到上述正則表達式的演示。
java 中的示例實現:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main
{
private static final Pattern pattern = Pattern.compile("^SutdentName:(\\w+),\\^StudenId:([^\\s,^:]+)$", Pattern.MULTILINE);
public static void main(String[] args) {
String string = "SutdentName:harry,^StudenId:Id123\n"
+ "SutdentName:harry,^StudenId:Id-H/MNK/U&T/BA+_T/(1490)/17@)123";
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
System.out.println(matcher.group(1) + " " + matcher.group(2));
}
}
}
您可以在此處找到上述代碼的示例運行。
第二個(\\w+?)
僅捕獲單詞。 所以改變它來捕捉你想要的東西。 IE
允許除: 和 ^ 和逗號以外的所有特殊字符
像([^:^,]+?)
^
- 否定匹配:^,
- 匹配:
, ^
和comma
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.