Javascript + ReactJS : Why doesn't regex . match() 返回不一致?

标签 javascript html regex reactjs

我使用 <pre> 显示以下多行字符串如下所示,其中每行都使用换行符表示:

SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem

我想解析build:e9kem出,并且每次多行的内容都会有所不同。但它会有build:在每一个。

我尝试过:

const regexp = /^build:(.*)$/m;

//stringPar would vary every time
const stringPar = `SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem`;

尝试像这样显示它:

{stringPar.match(regexp)[1])};

它解析正确,但对于某些多行字符串,它返回 Uncaught TypeError: Cannot read property '1' of null当我尝试显示诸如 stringPar.match(regexp)[1] 之类的字符串时,但当控制台像 console.log(stringPar.match(regexp)[1]) 这样进行控制台记录时,它会正确记录字符串。

可能是什么问题?

提前感谢您,并将投票/接受答案

编辑(在 ReactJS 中)

它基本上是一个一遍又一遍地渲染的组件, Prop 被传递到其中。

export default class tableRow extends Component {
     ...

     render() {
          console.log(this.props.stringPar.match(regexp)[1]);

          return (
               <tr>
                 <td>
                   {/*Even tried {this.props.stringPar.match(regexp)[1]==null? " ": this.props.stringPar.match(regexp)} but still getting the same error*/}
                   <button>{this.props.stringPar.match(regexp)[1]}</button>
                 <td>
               <tr>
          )
     }
}

最佳答案

What could possibly be the issue?

正则表达式并非在所有情况下都匹配,可能是因为:

every time the content of the multi-line will vary

执行类似的操作,以便您可以看到字符串不匹配时的样子:

export default class tableRow extends Component {
     ...

     render() {
          // ensure we actually have a string to run match on so don't get an error
          const matchStr = this.props.stringPar || ''; 
          const m = matchStr.match(regexp); // run match
          const matchFound = m && m.length > 0; // boolean, was match found
          const build = matchFound ? m[1] : 'build fallback'; // regex match or fallback if no match was found

          if (!matchFound) {
            console.log("Could not find 'build:' in:", matchStr, matchStr.length === 0 ? 'BLANK!' : 'NOT BLANK');               
          }

          return (
               <tr>
                 <td>
                   <button>{build}</button>
                 <td>
               <tr>
          )
     }
}

并相应地调整您的正则表达式。

关于Javascript + ReactJS : Why doesn't regex . match() 返回不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623246/

相关文章:

javascript - 如何将 Google map 上标记的像素位置映射为纬度和经度

javascript - document.getElementById ('a' ).click() 在 IE 中不起作用

php - 如何动态生成自创建页面?

python - 如何使用 python 从网站获取 XML 文件?

javascript - 在返回 response.json() promise 之前在 then() 方法中记录 response.json()

javascript - 如何从本地执行 HTML 和 Javascript *.bat 文件

html - 优雅的 CSS 间距定位

c# - 将 Xml 转换为 txt

javascript - 选择破折号后的所有内容 "-"RegEx || JavaScript

java - 使用 JAX-RS 的列表查询参数创建 URI