编程语言
首页 > 编程语言> > Java StreamTokenizer在@符号处拆分电子邮件地址

Java StreamTokenizer在@符号处拆分电子邮件地址

作者:互联网

我试图解析包含电子邮件地址的文档,但是StreamTokenizer将电子邮件地址分为两个单独的部分.

我已经将@符号设置为normalChar并将空格设置为唯一的空格:

StreamTokenizer tokeziner = new StreamTokenizer(freader);
tokeziner.ordinaryChar('@');
tokeziner.whitespaceChars(' ', ' ');

尽管如此,所有电子邮件地址仍被拆分.

要解析的行如下所示:

"Student 6 Name6 LastName6 del6@uni.at  Competition speech University of Innsbruck".

令牌生成器将del6@uni.at拆分为“ del6”和“ uni.at”.

有没有办法告诉令牌生成器不要在@符号处拆分?

解决方法:

所以这就是为什么它像以前那样工作:

StreamTokenizer将其输入视为编程语言令牌生成器.即,根据程序员为其设置的语法,将其分解为“单词”,“数字”,“带引号的字符串”,“注释”等的标记.程序员告诉它哪些字符是文字​​字符,普通字符,注释字符等.

因此,实际上,它确实进行了相当复杂的标记化-识别注释,带引号的字符串,数字.请注意,在编程语言中,您可以使用a = a b;之类的字符串.一个仅用空格将文本断开的简单分词器会将其分为a,=和b;.但是StreamTokenizer会将其分解为a,=,a,b和;,并且还会为您提供每个标记的“类型”,因此您的“语言”解析器可以将标识符与运算符区分开. StreamTokenizer的类型相当基本,但是此行为是了解您的情况的关键.

它没有将@识别为空格.实际上,它正在解析它并将其作为令牌返回.但是它的值在ttype字段中,您可能只是在看sval.

StreamTokenizer会将您的行识别为:

The word Student
The number 6.0
The word Name6
The word LastName6
The word del6
The character @
The word uni.at
The word Competition
The word speech
The word University
The word of
The word Innsbruck

(这是我编写的一个小样例的实际输出,该样例标记了您的示例行并按类型打印).

实际上,通过告诉@是一个“普通字符”,您是在告诉它以@作为其自己的令牌(无论如何默认情况下都会这样做). ordinaryChar() documentation告诉您此方法:

Specifies that the character argument is “ordinary” in this tokenizer.
It removes any special significance the character has as a comment
character, word component, string delimiter, white space, or number
character. When such a character is encountered by the parser, the
parser treats it as a single-character token and sets ttype field to
the character value.

(我的重点).

实际上,如果您改为将其传递给wordChars(),如tokenizer.wordChars(‘@’,’@’)一样,它将使整个电子邮件保持在一起.我添加的小演示给出了:

The word Student
The number 6.0
The word Name6
The word LastName6
The word del6@uni.at
The word Competition
The word speech
The word University
The word of
The word Innsbruck

如果您需要类似编程语言的令牌生成器,StreamTokenizer可能适合您.否则,您的选择取决于您的数据是否基于行(每行是一个单独的记录,每行上可能会有不同数量的令牌),在这种情况下,您通常会从读取器中逐行读取行,然后拆分使用String.split(),或者如果它们只是用空格分隔的令牌链,则Scanner可能更适合您.

标签:tokenize,email,stream,java
来源: https://codeday.me/bug/20191120/2042381.html