[英]Using Regular Expressions to Extract a Value in Java
我有幾個粗略的字符串:
[some text] [some number] [some more text]
我想使用 Java Regex 類提取 [some number] 中的文本。
我大致知道我想使用什么正則表達式(盡管歡迎所有建議)。 我真正感興趣的是 Java 調用以獲取正則表達式字符串並在源數據上使用它來生成 [某個數字] 的值。
編輯:我應該補充一點,我只對一個[某個數字](基本上是第一個實例)感興趣。 源字符串很短,我不會尋找[某個數字] 的多次出現。
完整示例:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
由於您正在尋找第一個數字,您可以使用這樣的正則表達式:
^\D+(\d+).*
和m.group(1)
將返回您的第一個數字。 請注意,有符號數可以包含減號:
^\D+(-?\d+).*
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex1 {
public static void main(String[]args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("hello1234goodboy789very2345");
while(m.find()) {
System.out.println(m.group());
}
}
}
輸出:
1234
789
2345
Allin 基本上有 java 代碼,所以你可以使用它。 但是,他的表達式僅在您的數字前面僅帶有單詞字符流時才匹配。
"(\\d+)"
應該能夠找到第一串數字。 如果您確定它將是第一個數字字符串,則無需指定它之前的內容。 同樣,除非您想要,否則指定其后的內容也沒有用。 如果您只想要數字,並且確定它將是一個或多個數字的第一個字符串,那么這就是您所需要的。
如果您希望它被空格抵消,那么指定它會更加明顯
"\\s+(\\d+)\\s+"
可能會更好。
如果您需要所有三個部分,這將執行以下操作:
"(\\D+)(\\d+)(.*)"
編輯Alllain 和 Jack 給出的表達式表明您需要指定一些非數字子集以捕獲數字。 如果您告訴正則表達式引擎您正在尋找\\d
那么它將忽略數字之前的所有內容。 如果 J 或 A 的表達式符合您的模式,則整個匹配項等於輸入字符串。 而且沒有理由指定它。 如果它沒有被完全忽略,它可能會減慢一場干凈的比賽。
在 Java 1.4 及更高版本中:
String input = "...";
Matcher matcher = Pattern.compile("[^0-9]+([0-9]+)[^0-9]+").matcher(input);
if (matcher.find()) {
String someNumberStr = matcher.group(1);
// if you need this to be an int:
int someNumberInt = Integer.parseInt(someNumberStr);
}
此函數從字符串中收集所有匹配的序列。 在這個例子中,它從字符串中獲取所有電子郵件地址。
static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";
public List<String> getAllEmails(String message) {
List<String> result = null;
Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);
if (matcher.find()) {
result = new ArrayList<String>();
result.add(matcher.group());
while (matcher.find()) {
result.add(matcher.group());
}
}
return result;
}
對於message = "adf@gmail.com, <another@osiem.osiem>>>> lalala@aaa.pl"
它將創建 3 個元素的列表。
// Regexplanation:
// ^ beginning of line
// \\D+ 1+ non-digit characters
// (\\d+) 1+ digit characters in a capture group
// .* 0+ any character
String regexStr = "^\\D+(\\d+).*";
// Compile the regex String into a Pattern
Pattern p = Pattern.compile(regexStr);
// Create a matcher with the input String
Matcher m = p.matcher(inputStr);
// If we find a match
if (m.find()) {
// Get the String from the first capture group
String someDigits = m.group(1);
// ...do something with someDigits
}
public class MyUtil {
private static Pattern pattern = Pattern.compile("^\\D+(\\d+).*");
private static Matcher matcher = pattern.matcher("");
// Assumptions: inputStr is a non-null String
public static String extractFirstNumber(String inputStr){
// Reset the matcher with a new input String
matcher.reset(inputStr);
// Check if there's a match
if(matcher.find()){
// Return the number (in the first capture group)
return matcher.group(1);
}else{
// Return some default value, if there is no match
return null;
}
}
}
...
// Use the util function and print out the result
String firstNum = MyUtil.extractFirstNumber("Testing4234Things");
System.out.println(firstNum);
嘗試做這樣的事情:
Pattern p = Pattern.compile("^.+(\\d+).+");
Matcher m = p.matcher("Testing123Testing");
if (m.find()) {
System.out.println(m.group(1));
}
看你可以使用 StringTokenizer
String str = "as:"+123+"as:"+234+"as:"+345;
StringTokenizer st = new StringTokenizer(str,"as:");
while(st.hasMoreTokens())
{
String k = st.nextToken(); // you will get first numeric data i.e 123
int kk = Integer.parseInt(k);
System.out.println("k string token in integer " + kk);
String k1 = st.nextToken(); // you will get second numeric data i.e 234
int kk1 = Integer.parseInt(k1);
System.out.println("new string k1 token in integer :" + kk1);
String k2 = st.nextToken(); // you will get third numeric data i.e 345
int kk2 = Integer.parseInt(k2);
System.out.println("k2 string token is in integer : " + kk2);
}
由於我們將這些數字數據放入三個不同的變量中,因此我們可以在代碼中的任何位置使用這些數據(以供進一步使用)
[^\\\\d]*([0-9]+[\\\\s]*[.,]{0,1}[\\\\s]*[0-9]*).*
我覺得會處理帶有小數部分的數字。 我包括空格和包括,
作為可能的分隔符。 我試圖從包含浮點數的字符串中獲取數字,並考慮到用戶可能會犯錯誤並在鍵入數字時包含空格。
有時您可以使用 java.lang.String 中提供的簡單 .split("REGEXP") 方法。 例如:
String input = "first,second,third";
//To retrieve 'first'
input.split(",")[0]
//second
input.split(",")[1]
//third
input.split(",")[2]
如果您正在從文件中讀取,那么這可以幫助您
try{
InputStream inputStream = (InputStream) mnpMainBean.getUploadedBulk().getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
//Ref:03
while ((line = br.readLine()) != null) {
if (line.matches("[A-Z],\\d,(\\d*,){2}(\\s*\\d*\\|\\d*:)+")) {
String[] splitRecord = line.split(",");
//do something
}
else{
br.close();
//error
return;
}
}
br.close();
}
}
catch (IOException ioExpception){
logger.logDebug("Exception " + ioExpception.getStackTrace());
}
Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)");
Matcher m = p.matcher("this is your number:1234 thank you");
if (m.find()) {
String someNumberStr = m.group(2);
int someNumberInt = Integer.parseInt(someNumberStr);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.