从字符串中提取第一个单词 - 正则表达式 [英] extract the first word from a string - regex

查看:109
本文介绍了从字符串中提取第一个单词 - 正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:

<预><代码>str1 = "猫一,猫2,猫3";或者str1 = "catone,cat-2,cat3";或者str1 = "卡通";或者str1 = "猫一";

这里的重点是单词中可能/可能没有-"

使用正则表达式:我怎么能提取第一个单词?

感谢您对此的任何帮助.

谢谢,

解决方案

很简单,只需在括号中包含允许的字符:

^([\w\-]+)

I have the following string:


str1 = "cat-one,cat2,cat-3";
OR
str1 = "catone,cat-2,cat3";
OR
str1 = "catone";
OR
str1 = "cat-one";

The point here is words may/may not have "-"s in it

Using regex: How could I extract the 1st word?

Appreciate any help on this.

Thanks, L

解决方案

It's pretty easy, just include allowed characters in brackets:

^([\w\-]+)

这篇关于从字符串中提取第一个单词 - 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆