简体   繁体   English

正则表达式删除了特殊字符

[英]Regex deleted special character

I'm having the following problem with regex: I've written a program that reads words from some text (txt) files and writes into another file, writing one word per line. 我正在使用正则表达式遇到以下问题:我编写了一个程序,它从一些文本(txt)文件中读取单词并写入另一个文件,每行写一个单词。

Everything works fine, except if the word read has a special characters ľščťžýáíé in it. 一切正常,除非读取的单词中包含特殊字符ľščťžýáíé The regex deletes the char and splits the word where the special char was. 正则表达式删除char并将特殊字符所在的单词拆分。

For Example : 例如 :
Input: 输入:

I am Jožo.

Output: 输出:

I
am
Jo
o

Here's a snippet of the code: 这是代码的片段:

while( (line = br.readLine())!= null ){ 
  Pattern p = Pattern.compile("[\\w']+");
  Matcher m = p.matcher(line);
}

Instead of this regex: 而不是这个正则表达式:

Pattern.compile("[\\w']+")

Use Unicode based: 使用基于Unicode:

Pattern.compile("[\\p{L}']+")

It is because by default \\\\w in Java matches only ASCII characters, digits 0-9 and underscore. 这是因为默认情况下,Java中的\\\\w仅匹配ASCII字符,数字0-9和下划线。

Another option is to use the modifier 另一种选择是使用修饰符

Pattern.UNICODE_CHARACTER_CLASS

Like this: 像这样:

Pattern.compile("[\\w']+", Pattern.UNICODE_CHARACTER_CLASS)

\\\\ w仅匹配az,AZ和0-9(英文字母加数字)如果要接受除空格之外的任何字符作为单词的一部分,请使用\\\\ S

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM