簡體   English   中英

在Java中使用正則表達式進行匹配?

[英]Matching using regular expressions in Java?

我希望在文本字符串中找到整個單詞。 字符串中的單詞由空格和換行符分隔,因此我使用了這兩個字符來查找每個單詞的開頭和結尾。 當模式為“ \\ s”或“ \\ n”時,程序會正確找到索引,而匹配兩個字符時則不會。 我該如何修復該程序?

import java.util.*;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class convertText{

    public static String findText(String text){

        String r = text.trim();

        // System.out.println(r);

        Pattern pattern = Pattern.compile("\\s+ | \\n");

        Matcher matcher = pattern.matcher(text);

    while (matcher.find()) {
        // System.out.println(matcher.start());
        System.out.println(text.substring(matcher.start()+1));
    }

        return text;
    }

    public static void main(String[] args) {
        // String test = " hi \n ok this. "; 
        String test = " hi ok this. "; 
        // System.out.println(test.substring(7));
        // System.out.println(test);
        findText(test);
    }


}

您可以使用[^\\\\s]+搜索不是換行符或空格的任何字符(又稱單詞)並打印組:

Pattern pattern = Pattern.compile("[^\\s]+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group());
}

[^\\\\s]+可細分為:

  • \\\\s匹配任何空格字符,包括常規空格和換行符(因此我們無需單獨指定\\\\n
  • []定義字符集 這將匹配括號內的任何字符
  • ^表示“不是”,因為字符集中的第一個字符會反轉匹配項,並且僅匹配不在集合中的字符(在這種情況下,除了空格和換行符之外的任何字符)。
  • +匹配一個或多個先前的標記,在這種情況下,先前的標記是與非空格字符匹配的字符表達式

您可以按照以下方式使用Java 8 Stream API進行操作

String test = " hi ok this. ";
Pattern.compile("\\W+").splitAsStream(test.trim())
            .forEach(System.out::println);

輸出:

hi
ok
this

如果要匹配文本字符串中的所有單詞,可以使用:

(?i)[az]+ java逃脫了: "(?i)[az]+"

(?i) ...打開不區分大小寫的匹配。
[az]+ ...盡可能匹配來自z的任何字母。

或者您可以使用:

\\w+ ...匹配ASCII letterdigitunderscore 盡可能多的次數。


    try {
        String subjectString = " hi ok this. ";
        Pattern regex = Pattern.compile("(?i)[a-z]+", Pattern.MULTILINE);
        Matcher regexMatcher = regex.matcher(subjectString);
        while (regexMatcher.find()) {
            String word = regexMatcher.group();
            int start_pos = regexMatcher.start();
            int end_pos = regexMatcher.end();
            JOptionPane.showMessageDialog(null, ""+word+ " found from pos: "+start_pos+" to "+end_pos);
        }
    } catch (PatternSyntaxException ex) {

    }

\\ s不匹配單個空格(僅)。 它匹配ASCII spacetabline feedcarriage returnvertical tabform feed 因此,您只需要\\ s +即可匹配各種空白字符。

只需用空格字符集分割字符串:

String[] words = yourString.split("\\s+");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM