java正则表达标点符号,Java正则表达式程序,用于在每个空格和标点符号处分割字符串。...

正则表达式“ [!._,'@?// s]”匹配所有标点符号和空格。

示例import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Test {

public static void main( String args[] ) {

String input = "This is!a.sample"text,with punctuation!marks";

Pattern p = Pattern.compile("[!._,'@?//s]");

Matcher m = p.matcher(input);

int count = 0;

while(m.find()) {

count++;

}

System.out.println("Number of matches: "+count);

}

}

输出结果Number of matches: 8

String类的split()方法接受一个表示正则表达式的值,并将当前字符串拆分为标记(单词)数组,将两次匹配之间的字符串视为一个标记。

例如,如果将单个空格“”作为分隔符传递给此方法,然后尝试拆分字符串。此方法将两个空格之间的单词视为一个标记,并在当前String中返回一个单词数组(空格之间)。

因此,要在每个空格和标点符号处分割字符串,请split()通过传递上面指定的正则表达式作为参数来调用该方法。

示例import java.util.Scanner;

import java.util.StringTokenizer;

public class RegExample {

public static void main( String args[] ) {

String regex = "[!._,'@? ]";

System.out.println("Enter a string: ");

Scanner sc = new Scanner(System.in);

String input = sc.nextLine();

StringTokenizer str = new StringTokenizer(input,regex);

while(str.hasMoreTokens()) {

System.out.println(str.nextToken());

}

}

}

输出结果Enter a string:

This is!a.sample text,with punctuation!marks@and_spaces

This

is

a

sample

text

with

punctuation

marks

and

spaces

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值